Reputation: 7970
I have a Polymer core-ajax
component sending some data to a Node.js server. The data is being sent correctly (I can parse it with a Go web server) but Node parses it as the stringified body being a key to a blank string in a JSON object:
{ '{"count":-1,"uid":1}': '' }
This is the code that sends the request from 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();
}
This is the Node code:
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));
});
When I get the response back it has returned the malformed JSON.
How am I supposed to parse JSON in Node correctly?
Also:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Upvotes: 6
Views: 1547
Reputation: 1101
Set the core-ajax
attributes contentType="application/json"
and handleAs="json"
and stringify the JSON before setting it as ajax.body
.
Upvotes: 4