所以客户端js只发送带有JSON对象的POST
。$.ajax({
type: 'POST',
url: '/onadd',
data: addJsonObj.toJSON,
success: function(){
console.log("Task added!", data);
}
});
到我的 nodeJS 服务器。
我在 nodeJS 服务器上看到我的传入请求。那么如何从我的 nodeJS 服务器上的请求中解析 JSON 对象呢?需要这样的 smth:
if(request.method == 'POST' && request.url == '/onadd'){
var jsonObj = JSON.parse(request.body); //can't parse JSON here!(
console.log(jsonObj.task);
console.log('hoorayyyy!!!!!!'); //got this!
}
你必须声明数据类型
$.ajax({
type: 'POST',
url: '/onadd',
data: addJsonObj.toJSON,
dataType: "json",
success: function(){
console.log("Task added!", data);
}
});
您需要
按照@Matthieu建议的方式设置dataType
:
$.ajax({
type: 'POST',
url: '/onadd',
data: JSON.stringify(addJsonObj),
dataType: 'json',
success: function(){
console.log('Task added!', data);
}
});
您还需要像这样流式传输请求正文:
if(request.method == 'POST' && request.url == '/onadd'){
var json = '';
request.on('data', function (chunk){
json += chunk.toString('utf8');
});
request.on('end', function (){
console.log(json);
var jsonObj = JSON.parse(json);
console.log(jsonObj.task);
});
}