ajax – Node.js / Express POST请求正文解析为不正确的JSON

前端之家收集整理的这篇文章主要介绍了ajax – Node.js / Express POST请求正文解析为不正确的JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个Polymer core-ajax组件将一些数据发送到Node.js服务器.数据正在正确发送(我可以使用Go Web服务器解析它),但Node将其解析为字符串化主体是 JSON对象中空字符串的键:
{ '{"count":-1,"uid":1}': '' }

这是从Polymer发送请求的代码

sendCount: function(change) {
  console.log("Sending...");
  console.log(JSON.stringify({"count": change,"uid": this.uid}));
  // ^ This prints: {"count":-1,"uid":1}
  this.$.ajax.body = JSON.stringify({"count": change,"uid": this.uid});
  this.$.ajax.go();
}

这是节点代码

app.post("/post",function(req,res) {
  console.log(res.headers);
  console.log(req.body); // Prints { '{"count":-1,"uid":1}': '' }
  res.setHeader('Content-Type','application/json');
  res.end(JSON.stringify(req.body));
});

当我收到回复时,它返回了格式错误的JSON.

我该如何正确解析Node中的JSON?

也:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

解决方法

在将其设置为ajax.body之前,设置core-ajax属性contentType =“application / json”和handleAs =“json”并对JSON进行字符串化.

猜你在找的Ajax相关文章