I want to run code in a .then() after a fetch() resolves, the issue is that my .then() does not run after the POST method resolves, it does however if it rejects.
What I am doing is sending a mail through my server using Nodemailer. So I'm not entirely sure what the issue is but perhaps Nodemailer doesn't return a promise to the call or it takes too long and therefore it only runs .then() if it rejects. Does anyone know what the issue is and how it can be solved or perhaps if there are alternative ways that I can run some code after the fetch() has resolved?
Form submission:
const handleSubmit = (e) => {
e.preventDefault();
fetch("http://localhost:4000/send_mail", {
method: 'POST',
body: formData
}).then((res) => {
//This does not run on resolve
if (res.ok)
{ }
});
}
Server:
app.post("/send_mail", cors(), async (req, res) => {
await transport.sendMail({
from: sender,
to: receiver,
subject: "Subject",
html: ``,
attachments: [{
filename: filename,
content: content
}
})
});
Send a response from your server:
transport.sendMail({
// mailoptions
}, (err, data) => {
if (err) {
console.log(err);
res.status(400).send('Error');
} else {
res.status(200).send('Success');
}
})
The problem is that your server-side code does not send any response, so the request itself hangs infinitely until the request times out either server-side or client-side. So the then will never be called instead an error will happen at some point on the client-side.
Your server-side code should look like this:
app.post("/send_mail", cors(), async (req, res) => {
try {
await transport.sendMail({
from: sender,
to: receiver,
subject: "Subject",
html: ``,
attachments: [{
filename: filename,
content: content
}
})
res.status(200).send('Success');
} catch (err) {
// some kind of error response, you need to decide
// which status code is the propper one
res.status(500).send('Error');
}
});