Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Return promise from Fetch when posting through Nodemailer

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
    }
  })
});
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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');
    }
})
about 4 years ago · Juan Pablo Isaza Report

0

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');
  }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!