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)
})
}
You have several problems in this code:
sendMail out of your handler, it has no idea what res is.transporter.sendMail does not return a Promise, hence you can't await it, but you still can promisify it.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()
})
})
}
history.push to change route, but something like react-router to perform client-side navigation.