Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
How to redirect after Nodemailer POST request

I have an app with a React frontend, and an Express backend. I have a form setup with Nodemailer that sends an email after the user submits the form. I want to trigger a redirect after submission depending on whether the email was sent successfully or not. The emails send just fine, however the redirect does not. Anyone know what I'm doing wrong?

Post Request Handler

app.post('/sendApplication', cpUpload, async (req) => {
    await sendMail(req.files['essay'][0], req.files['recLetter1'][0], req.files['recLetter2'][0], req.body)
})

Nodemailer Code (My mail options are also here, but I omitted them since they're irrelevant)

const sendMail = async () => {
    
        await transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                console.log(error)
                res.sendStatus(500)
            } else {
                console.log("Message Sent " + info.response)
                res.sendStatus(200)
            }
        })
}

Front End Code

handleRedirect = (res) => {
    if (res.status === 200) {
        this.props.history.push('/success')
    } else {
        this.props.history.push('/applicationerror')
    }
}

handleSubmit = async (e) => {
    e.preventDefault()
    let formData = new FormData()
    for (let i in this.state.formValues) {
        formData.append(i, this.state.formValues[i])
    }
    formData.append('essay', document.getElementById('essay').files[0])
    formData.append('recLetter1', document.getElementById('recLetter1').files[0])
    formData.append('recLetter2', document.getElementById('recLetter2').files[0])
    fetch('/sendApplication', {
        method: 'POST',
        body: formData
    }).then((res) => {
        this.handleRedirect(res)
    })
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have several problems in this code:

  1. Your route handler is the one that has access to the response stream, if you declare sendMail out of your handler, it has no idea what res is.
  2. transporter.sendMail does not return a Promise, hence you can't await it, but you still can promisify it.
  3. You are passing the files taken from multer and the body of the request to sendMail but it's not actually taking any parameter in.
app.post('/sendApplication', cpUpload, async (req) => {
try {
      await sendMail()
      res.sendStatus(200)
     } catch(e){
      console.log(e)
      res.sendStatus(500)
     }
})

sendMail

const sendMail = () => {
    ...
    ...
    return new Promise((resolve, reject) => {
      transporter.sendMail(mailOptions, function (err) {
        if (err) reject(err)
        else resolve()
      })
    })
}
  1. You shoud not use history.push to change route, but something like react-router to perform client-side navigation.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda