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

6

我有一个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();
}

这是Node代码:
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 }));

1
ajax.body设置为对象,而不是JSON.stringify(object) - aarosil
1
你设置了 core-ajax 属性 contentType="application/json"handleAs="json" 吗?我是这样做的,将 JSON 字符串化后将其设置为 ajax.body,它在 node 中运行良好。 - idleherb
1
@idleherb,搞定了。想把它提交为答案吗? - Will Richardson
很高兴能帮到你,谢谢伙计! - idleherb
1个回答

4

core-ajax属性设置为contentType="application/json"handleAs="json",并在设置ajax.body之前将JSON字符串化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接