Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js/ Express POST Request Body Parsed into Incorrect JSON

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 }));
like image 230
Will Richardson Avatar asked Mar 27 '15 07:03

Will Richardson


People also ask

Does Express automatically parse JSON?

By default, you won't be able to parse JSON from the body of an incoming request with Express.

How do I read JSON Request body in node JS?

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.

How do I read a JSON file in node JS?

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.


1 Answers

Set the core-ajax attributes contentType="application/json" and handleAs="json" and stringify the JSON before setting it as ajax.body.

like image 184
idleherb Avatar answered Oct 08 '22 15:10

idleherb