admin管理员组文章数量:1122832
Ive written a small webpage and when i send my email to the back end it sends it
font-end
step 1
async function userSend()
{
let input=document.getElementById("email").value;//save this as an object
//window.alert(input);
//loading();
console.log("here3");
const res=await fetch(userD1,
{
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
Email:input
})
});
}
I call the function when a user clicks a button thats linked to createAccount()
step2
async function createAccount()
{
await userSend();//will tell you its sent
let user=await userCheck();
}
It goes to the server where i collect it
step3
app.post("/collectEmail",(req,res)=>
{
emailC=req.body;
found=find1(emailC);
console.log(emailC.Email+" Is collected from the front-end");
})
I find the data on mongo db and send it back.
My front end is still stuck on step one. Im not sure what the problem is
The mongo connection code and findOne() works and displays outputs on my sever console.
I expect to send the data from the front to the back it gets checked and then sent back to the front where i display if the account exists or not.
Not sure what ive done wrong here
I have a lot of setInteval and Timeouts running on my front-end. If i have not cleared one could it stall my async functions when trying to receive data from the server.
Ive written a small webpage and when i send my email to the back end it sends it
font-end
step 1
async function userSend()
{
let input=document.getElementById("email").value;//save this as an object
//window.alert(input);
//loading();
console.log("here3");
const res=await fetch(userD1,
{
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
Email:input
})
});
}
I call the function when a user clicks a button thats linked to createAccount()
step2
async function createAccount()
{
await userSend();//will tell you its sent
let user=await userCheck();
}
It goes to the server where i collect it
step3
app.post("/collectEmail",(req,res)=>
{
emailC=req.body;
found=find1(emailC);
console.log(emailC.Email+" Is collected from the front-end");
})
I find the data on mongo db and send it back.
My front end is still stuck on step one. Im not sure what the problem is
The mongo connection code and findOne() works and displays outputs on my sever console.
I expect to send the data from the front to the back it gets checked and then sent back to the front where i display if the account exists or not.
Not sure what ive done wrong here
I have a lot of setInteval and Timeouts running on my front-end. If i have not cleared one could it stall my async functions when trying to receive data from the server.
Share Improve this question edited Nov 21, 2024 at 15:40 Smiley_Guy asked Nov 21, 2024 at 15:31 Smiley_GuySmiley_Guy 218 bronze badges 4- "Stuck" in what way? Please elaborate on the specific problem you are observing and what debugging you have done. – David Commented Nov 21, 2024 at 15:46
- My front-end does not recieve any data from the back-end. Its stuck on the post/fetch – Smiley_Guy Commented Nov 21, 2024 at 17:02
- 1 The back-end code doesn't appear to ever send data (or any response at all) to the front-end. Did you simply forget that step? Possibly just a typo or oversight when referencing code from whatever tutorials or examples you're using? – David Commented Nov 21, 2024 at 17:07
- @David hello, its working now. I might be wrong but what I've noticed is that the reason why the post promise hadn't resolved is because it need to have the res receive on the front-end. It all works I send and receive data. The only issue i have not after a certain amount of time my server cuts out and i get a mongo connection issue. I have a boolean switch passed into a function when ever i need to open mongo and when i close it i just set the switch to false. Not sure how exactly mongo communicates with node JS and what conditions they are using. Will figure it out – Smiley_Guy Commented Nov 22, 2024 at 19:03
1 Answer
Reset to default 1I think you're missing the return of the response from the backend.
Here's some updated code with additional error handling:
// Frontend (Client-side)
async function userSend() {
try {
const input = document.getElementById("email").value;
// Validate email before sending
if (!input || !input.includes('@')) {
throw new Error('Invalid email address');
}
const res = await fetch('/collectEmail', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ Email: input })
});
// Check if response is successful
if (!res.ok) {
throw new Error('Server response was not ok');
}
const data = await res.json(); // Parse the response
// Handle the result
if (data.exists) {
// Account already exists
displayMessage('Account already exists');
} else {
// Account can be created
displayMessage('Account can be created');
}
} catch (error) {
console.error('Error:', error);
displayMessage(error.message);
}
}
function displayMessage(message) {
const messageElement = document.getElementById('message');
messageElement.textContent = message;
}
// Backend (Server-side, Express with MongoDB)
app.post("/collectEmail", async (req, res) => {
try {
const emailC = req.body;
const found = await find1(emailC.Email);
// Send back a clear response
res.json({
exists: !!found, // Convert to boolean
message: found ? 'Account exists' : 'Account available'
});
} catch (error) {
console.error('Server error:', error);
res.status(500).json({
exists: false,
message: 'Server error occurred'
});
}
});
// Improved find1 function (assuming mongoose)
async function find1(email) {
try {
return await User.findOne({ email: email });
} catch (error) {
console.error('Database lookup error:', error);
throw error;
}
}
本文标签: nodejsStuck on fetch frontendStack Overflow
版权声明:本文标题:node.js - Stuck on fetch front-end - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736309428a1934018.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论