【发布时间】:2016-03-31 19:13:41
【问题描述】:
我通过 AJAX 发送到我的服务器 nodejs,这个 JS 在客户端:
function login(){
var array=[];
var jsonData={};
jsonData.user=$('#user').val();
jsonData.pass=$('#pass').val();
array.push(jsonData);
console.log(JSON.stringify(array));
$.ajax({
method:'POST',
url: 'auth',
dataType: 'application/json',
data: JSON.stringify(array)
}).done(function(msg){
alert( "Data Saved: " + msg );
});
}
可以看到,在发送ajax之前,浏览器输出控制台是:
[{"user":"User001","pass":"SecretPassword"}]
在服务器端,我有这个代码:
router.post('/', function(req, res, next){
console.log(req.body);
// { '[{"user":"User001","pass":"SecretPassword"}]': '' }
console.log(JSON.parse(req.body));
// {"[{\"user\":\"User001\",\"pass\":\"SecretPassword\"}]":""}
res.sendStatus(202);
}
但是,如果我使用 Postman 测试此 Web 服务,我的服务器会正确接收 Json 数据: Screen capture
请,有人帮助我吗??我尝试解决这个问题大约 2 天 :(
【问题讨论】:
-
如果您发送的是 json,您应该将内容类型设置为 json
-
是的。请看第一个代码片段:dataType: 'application/json',
-
那不是内容类型,dataType是别的东西
-
非常感谢。解决了:)
标签: javascript json ajax node.js