我正在使用 express 3.0 和节点 v0.11.0。我有一个提交表单的按钮,我正在使用 ajax 将该数据作为 JSON 对象发布到我的节点服务器。
客户端代码为:
$('#contact').submit(function(e) {
console.log('submit called');
var formData = JSON.stringify($('form').serializeObject());
console.log(formData);
$.ajax({
url: "http://localhost:3000/savedata/",
type: "POST",
dataType: 'json',
data: {objectData: formData},
contentType: "application/json",
complete: function() {
console.log('process complete');
},
success: function(data) {
console.log('process sucess');
},
error: function() {
console.log('process error');
},
});
return false;
});
然后在我的服务器上:
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.static(__dirname + '/public', {maxAge: 86400000}));
app.engine('.jade', require('jade').__express);
app.post('/savedata', function(req, res) {
console.log('savedata called');
console.log(req.body);
//var resultObject = JSON.parse(req.body.objectData);
//console.log(resultObject);
res.end();
});
我面临的问题是,当我使用 express.bodyParser() 中间件时,我得到一个:
Error: Bad Request
at next (/home/captain/data/lemontreecakes/node_modules/express/node_modules/connect/lib/proto.js:125:13)
at /home/captain/data/lemontreecakes/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:54:23
at IncomingMessage.<anonymous> (/home/captain/data/lemontreecakes/node_modules/express/node_modules/connect/lib/middleware/json.js:74:60)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:883:14
at process._tickCallback (node.js:415:13)
这是我浏览器中的控制台输出:
submit called load.js:33
{"name":"tes","email":"tets@est.com"} load.js:36
POST http://localhost:3000/savedata/ 400 (Bad Request) jquery-1.9.1.min.js:5
process error load.js:54
process complete
所以我知道我正在向我的服务器提交数据。如果我从节点服务器中删除主体解析器中间件,那么我会得到
savedata called
TypeError: Cannot read property 'objectData' of undefined
我在想我没有正确地将 JSON 数据发送到服务器。任何提示将不胜感激。