Reputation: 35
I have an app written with React as the frontend, and Express as the backend. I'm using Nodemailer to email out the results of a form. It hits the backend and sends out just fine, but I'm looking for the proper way to send a response back to the front end so that I can alert the user if there's an error, or redirect to a success page if it goes through fine. I've tried both using a callback function and omitting it in my transporter.sendMail() code and neither have worked. I don't really know what I'm doing, and could use some help.
Transporter Code (Wrapped inside my sendMail function)
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err)
res.sendStatus(500)
} else {
console.log(info)
res.sendStatus(201)
}
})
Server Code
app.post('/sendApplication', cpUpload, async (req, res) => {
return sendMail(req.files['essay'][0], req.files['recLetter1'][0], req.files['recLetter2'][0], req.body)
})
Form Submit Code
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])
await fetch('/sendApplication', {
method: 'POST',
body: formData
}).then((res) => {
if (res.ok) {
window.localStorage.removeItem('applicationData')
this.props.history.push('/success')
} else {
alert('Error Message')
}
})
}
Upvotes: 1
Views: 434
Reputation: 2702
First, you need to add (req,res,next)
in you controller function to use res function.
After this, you will be able to return res to the client.
Try this :
const sendMail = (res,req,next) => {
///
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err)
res.status(500).send({err : err})
} else {
console.log(info)
res.status(200).send({success : info})
}
})
///
}
Upvotes: 0