我创建了一个联系表单,它将get请求发送到我从节点(快速)服务器本地托管的路由。我在dom上点击一个元素时发送get请求。
($(document).ready(function () {
$('#sendEmail').click((e) => {
e.preventDefault();
let name = $('#name').val();
let email = $('#email').val();
$.get("http://localhost:3000/send", {name: name, email: email})
.done(() => {
alert('success!');
})
.fail(() => {
alert('That did not work');
})
})($)
节点服务器根据从客户端收集的信息生成电子邮件。好消息是生成的电子邮件运行正常,并使用nodemailer通过电子邮件发送到我的Gmail帐户。
app.get('/send', (req, res) => {
const mailOptions = {
name: req.query.name,
email: req.query.email,
message: req.query.message,
to: "",
from: req.query.name,
text: ""
}
smtpTransport.sendMail(mailOptions, (error, response) => {
if (error) {
console.log(error);
response.end('error');
} else {
console.log('Email sent!');
response.end('sent')
}
})
})
一切都是成功的服务器端,但之后没有客户端代码运行。我的$ .done()函数或我的$ .fail()函数都没有运行。我需要做什么才能在电子邮件发送(或不发送)后运行客户端代码?
答案 0 :(得分:0)
因为您没有将结果回复给客户 你需要在'sendMail'的回调中调用'res'而不是'response':
app.get('/send', (req, res) => {
const mailOptions = {
name: req.query.name,
email: req.query.email,
message: req.query.message,
to: "",
from: req.query.name,
text: ""
}
smtpTransport.sendMail(mailOptions, (error, response) => {
if (error) {
console.log(error);
//response.end('error');
res.end('error'); // <=====================
} else {
console.log('Email sent!');
//response.end('sent')
res.end('Email sent!'); // <=====================
}
})
})