我使用Express 3.0和節點v0.11.0。我有一個提交表單的按鈕,我使用ajax將該數據作爲JSON對象發佈到我的節點服務器。
的客戶端代碼:錯誤的請求 - 節點js ajax後
$('#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":"[email protected]"} 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數據到服務器。任何提示將不勝感激。
不要在表單數據上使用'JSON.stringify',而是直接將序列化表單數據作爲'data'參數傳遞。 – CBroe