I am trying to set up a really simple contact form with nodemailer and it works fine, but my issue is that it doesn't handle errors. The page should redirect if an error is thrown, but instead the redirect does not happen and the app stops running. I cannot for the life of me figure out why this is happening. Here is my code:
if (req.method === 'POST') {
const name = req.body.name;
const email = req.body.email;
const msg = req.body.message;
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myemail', // left out here
pass: process.env['GMAIL_PASS']
}
});
const mailOptions = {
from: 'myemail', // left out here
to: 'myemail', // left out here
subject: 'Portfolio Inquiry',
text: `
Name: ${name}
Email: ${email}
Message:${msg}`
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
// If an error is thrown, it should redirect back to the page with a fail message
return res.redirect('/about?send=fail#contact');
} else {
return res.redirect('/about?send=success#contact');
}
});
}
If I introduce an error into the script by commenting out something important or just throwing an error, as I said the error handling block in the sendMail
callback doesn't do anything. As I said, it does properly work and send the email, but if something went wrong I definitely want my user to know about it. Could anyone help me understand how to correct this issue?