环境:
- >前端:randle ajax请求的jquery
- >后端:nodejs,expressjs(v.3.4.8)。
我尝试创建一个简单的联系表单。
我的前端代码:
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: { info: JSON.stringify(info) }
}).done(function(retorno){
//do something important
});
这项工作很好,我测试过并且在firebug上从前端开始的一切都很好。
但我不知道如何处理需要从帖子请求中读取json的快递。
我就拥有它:
app.post('/contact', function(req, res){
});
答案 0 :(得分:0)
问题在于:
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
只需将JSON''更改为“”即可正常工作。我来自php和php在JSON上识别''和'“,但nodejs只是严格识别”“。
经过一些编码后,简单的联系表格示例的结果是:
在common.js文件中(前端):
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {"nome":nome, "email":email, "assunto":assunto, "mensagem":mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: JSON.stringify(info),
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(retorno){
//do something at the end
}
在文件app.js或server.js或其他任何内容中(后端):
var http = require("http")
, express = require('express')
, nodemailer = require('nodemailer')
, app = express();
app.use(express.json());
app.use(express.static(__dirname+'/public'));
app.post('/contact', function(req, res){
var name = req.body.nome;
var email = req.body.email;
var subject = req.body.assunto;
var message = req.body.mensagem;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "your.user@gmail.com",
pass: "your.password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'recipe.email@gmail.com',
subject: subject,
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(80, '127.0.0.2');
从此示例中:http://blog.ragingflame.co.za/2012/6/28/simple-form-handling-with-express-and-nodemailer