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 }));
By default, you won't be able to parse JSON from the body of an incoming request with Express.
JSON Request Body Express has a built-in express. json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req . To access the parsed request body, use req.
The simplest way to read a JSON file is to require it. Passing require() with the path to a JSON file will synchronously read and parse the data into a JavaScript object. const config = require("./config.
Set the core-ajax
attributes contentType="application/json"
and handleAs="json"
and stringify the JSON before setting it as ajax.body
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With