我正在尝试使用JQUery从客户端向使用NodeJS上的ExpressJS的服务器发送JSON数据。但是我收到了一个错误:
客户代码:
var data = {
title: "title",
message: "message"
};
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: '/testData',
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
服务器代码:
app.post('/testData', function(req, res) {
var x = JSON.parse(req.body);
console.log(x);
});
错误:
SyntaxError: Unexpected token u
at Object.parse (native)
at C:\Users\Me\WebstormProjects\untitled\app.js:63:22
at callbacks (C:\Users\Me\WebstormProjects\untitled\node_modules\express\lib\router\index.js:164:37)
at param (C:\Users\Me\WebstormProjects\untitled\node_modules\express\lib\router\index.js:138:11)
at pass (C:\Users\Me\WebstormProjects\untitled\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\Users\Me\WebstormProjects\untitled\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\Users\Me\WebstormProjects\untitled\node_modules\express\lib\router\index.js:33:10)
at next (C:\Users\Me\WebstormProjects\untitled\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.logger (C:\Users\Me\WebstormProjects\untitled\node_modules\express\node_modules\connect\lib\middleware\logger.js:158:5)
at next (C:\Users\Me\WebstormProjects\untitled\node_modules\express\node_modules\connect\lib\proto.js:193:15)
我也无法从JSON中解析单个值以进行工作 - 双方都是。
- 更新 -
虽然上述问题已经解决,但我无法发送像
这样的复杂对象var data = {
num1: 100,
num2: {
num3: 100,
num4: 250
}
};
服务器可以从body.num1读取num1但不能从body.num2.num3和body.num2.num4读取num3和num4。 console.log上只显示“[object] [object]”