我想在通过 nodemailer 发送电子邮件后使用 HTML 显示确认消息。我对 Node 相当陌生,所以我不确定我是否遗漏了一些明显的东西。
app.post("/bye", function(req, res){
// send e-mail
var transporter = nodemailer.createTransport({
...
});
var mailOptions = {
...
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
... (Something here that is going to print a confirmation message to the html code of the page)
});
res.end("yes");
});
谢谢
最佳答案
Node 完全独立于浏览器运行,因此您无法直接从 Node 修改浏览器中的 HTML。您需要将响应从 Node 发送到浏览器,然后在浏览器中处理该响应。它可能会像这样工作......
Node
app.post("/bye", function(req, res){
// send e-mail
var transporter = nodemailer.createTransport({
...
});
var mailOptions = {
...
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error)
res.end({
success: false,
msg: error
});
}
console.log('Message sent: ' + info.response);
res.end({
success: true
});
});
});
然后在您的客户端 javascript 中(为了简单起见,使用 jQuery post,但使用普通的 javascript 请求,或者如果您愿意的话使用其他库)...
$.post('/bye').then(function(response) {
if (response.success) {
$('#msg').text('Your message was sent');
} else {
$('msg').text(response.msg);
}
}).catch(function(err) {
$('#msg').text('Could not reach server');
});
关于javascript - Node.js 使用回调函数更改 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41018766/