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

Wil*_*son 5 ajax json node.js polymer

我有一个Polymer core-ajax组件将一些数据发送到Node.js服务器.数据正在正确发送(我可以使用Go Web服务器解析它),但Node将其解析为字符串化主体是JSON对象中空字符串的键:

{ '{"count":-1,"uid":1}': '' }
Run Code Online (Sandbox Code Playgroud)

这是从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();
}
Run Code Online (Sandbox Code Playgroud)

这是节点代码:

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));
});
Run Code Online (Sandbox Code Playgroud)

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

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

也:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Run Code Online (Sandbox Code Playgroud)

idl*_*erb 4

设置core-ajax属性contentType="application/json"并对handleAs="json"JSON 进行字符串化,然后再将其设置为ajax.body.