我有一个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)); });
我该如何正确解析Node中的JSON?
也:
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
解决方法
在将其设置为ajax.body之前,设置core-ajax属性contentType =“application / json”和handleAs =“json”并对JSON进行字符串化.