我正在尝试使用节点发送测试电子邮件。
我的服务器代码index.js如下所示:
var http = require("http"),
express = require('express'),
nodemailer = require('nodemailer'),
bodyParser = require('body-parser'),
app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.post('/contact', function (req, res) {
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "email@gmail.com",
pass: "password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'cmatsoukis@gmail.com',
subject: "Website Contact",
text: message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.send(false);
}
//Yay!! Email sent
else {
res.send(true);
}
});
});
app.listen(1337, '127.0.0.2');
这是我提交表格时的ajax代码
var form = $("form#contact_form");
form.submit(function () {
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var msg = $('#message').val();
var info = {"name" : name, "email": email, "message" : msg}
$.ajax({
url: 'http://127.0.0.2:1337',
type: 'POST',
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
jsonpCallback: 'callback', // this is not relevant to the POST anymore
//dataType: 'json',
success: function (data) {
MailSuccess()
lightSpeed();
},
error: function () {
MailFail();
}
});
});
我收到错误 POST http://127.0.0.2:1337/ 404 (Not Found)
我认为我没有正确的网址。我有app.post('/contact', function (req, res) {
但我不这是正确的。我不应该在url: 'http://127.0.0.2:1337',
?
我相信我还有其他一切正确。请告诉我。
答案 0 :(得分:2)
您已为'/contact'
注册了POST处理程序,但您正在向'/'
发出请求。
由于您尚未告知明确要对'/'
做什么,因此会返回Not Found。
使两条路径匹配。