Reputation: 123
Trying to get my page to redirect from a node.js and express.js page after sending an email. The message gets sent and I am getting the console.log() in my terminal (using morgan for logging) but it's not redirecting me to the success page and I'm not getting a console.log error in the browser. It just stalls and then i get a localhost didn't send any data error. Never used nodemailer before but I managed to get the message sent, I'm just having a problem redirecting to a new page.
Thanks!!
//Success html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
// Form Box
<form action="/contact" id="contact-form" method="post" role="form">
<fieldset>
<label for="name">Name *</label>
<input id="name" name="name" type="text" placeholder="Your name" required="required">
<label for="email">Email *</label>
<input id="email" name="email" type="text" placeholder="Your email" required="required">
<label for="message">Message *</label>
<textarea id="message" name="message" placeholder="Enter your message here" rows="3" required="required"></textarea>
<button type="submit">Submit</button>
</fieldset>
</form>
// Success HTML route
app.get('/success', function(req,res){
res.sendFile(__dirname + '/views' + '/success.html');
});
//nodemailer // POST route from contact form
app.post('/contact', function (req, res) {
let mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: process.env.GMAIL_USER,
pass: process.env.GMAIL_PASS
}
});
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: process.env.GMAIL_USER,
subject: 'New message from Portfolio site',
text: `${req.body.name} (${req.body.email}) says: ${req.body.message}`
};
smtpTrans.sendMail(mailOpts, function (error, res) {
if (error) {
return console.log(error);
}
else {
console.log('success');
res.redirect('/success');
}
});
});
Upvotes: 2
Views: 1671
Reputation: 162
wondering if you still stuck on the issue but in case, below worked for me.
app.post('/contact', function (req, res) {
let mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: process.env.GMAIL_USER,
pass: process.env.GMAIL_PASS
}
});
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: process.env.GMAIL_USER,
subject: 'New message from Portfolio site',
text: `${req.body.name} (${req.body.email}) says: ${req.body.message}`
};
smtpTrans.sendMail(mailOpts, function (error, res) {
if (error) {
return console.log(error);
}
else {
console.log('success');
// NOT HERE res.redirect('/success');
}
});
res.redirect('/success'); // I MOVED THE REDIRECTING CODE HERE AND WORKED
});
Upvotes: 2