1
I am beginner learning Node.js and I am caught in a question of sending email on the site as if it were that ''contact us'' using Node.js
The point is, I can send the email, but it only sends when the page gives error and does not update. Displays the message on the screen "Cannot POST /index''
But if I get this problem to direct to the page itself (in this case, index), it does not send the email, I can not understand, could help me?
The way I’ll put in the example it sends the email, but returns a page with the error reported ("Cannot POST /index"), but if I fix this by putting in the server.js:
app.use('/index', require('./routes/index'));
Email is not sent. And if I take action or leave action = /' in Html, it returns the right page, but does not send the email either.
Note: I am using express
server.js
const nodemailer = require('nodemailer');
var enviar = function(req, res, next) {
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: '123'
}
});
var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Nome: ' + req.body.nome + ' / Telefone: ' + req.body.telefone,
text: req.body.mensagem
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
next();
};
app.use(enviar);
index.html
<form method="POST" action="/index">
<div class="image fit">
<h3>Nos envie uma mensagem!</h3>
<textarea name="mensagem"></textarea>
</div>
Nome: <input type="text" name="nome" />
<br>
Telefone: <input type="text" name="telefone" />
<br>
<footer>
<button class="button special" onclick="enviar()">Enviar</button>
</footer>
</form>