Node.js/ 表达 POST 请求正文解析为错误 JSON
Node.js/ Express POST Request Body Parsed into Incorrect JSON
我有一个 Polymer core-ajax
组件向 Node.js 服务器发送一些数据。数据被正确发送(我可以用 Go 网络服务器解析它)但是 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 }));
设置 core-ajax
属性 contentType="application/json"
和 handleAs="json"
并在将 JSON 设置为 ajax.body
之前将其字符串化。
我有一个 Polymer core-ajax
组件向 Node.js 服务器发送一些数据。数据被正确发送(我可以用 Go 网络服务器解析它)但是 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 }));
设置 core-ajax
属性 contentType="application/json"
和 handleAs="json"
并在将 JSON 设置为 ajax.body
之前将其字符串化。