Nicola
Nicola

Reputation: 389

Retrieve JSON from HTTP POST request

I have the following function (essentially taken straight from the answer to another SO question):

function makePostRequest(requestURL, postData) {
  request(
  {
   url: requestURL,
   method: "POST",
   json: true, 
   body: postData
  },
  function(error, response, body) {
   console.log(response);
  });
}

When I call it with the right requestURL, I successfully reach this route:

router.post("/batchAddUsers", function(req, res) {
  console.log("Reached batchAddUsers");
});

I've been trying to retrieve the postData I sent with the request to no avail. Both req.params and req.body are {}. I haven't got the faintest clue how to refer to the object containing body passed in the request.

I read the whole console.log(req) and found nothing useful. I've done this kind of stuff before, except the request was made by a form and req.body worked like a charm. Now that I'm doing the request "manually", it doesn't work anymore. The whole thing is running on Node.js.

What am I doing wrong?

Upvotes: 1

Views: 172

Answers (1)

Sangram Badi
Sangram Badi

Reputation: 4264

I think you did not insttalled body-parser

To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser.

body-parser extract the entire body portion of an incoming request stream and exposes it on req.body .

The middleware was a part of Express.js earlier but now you have to install it separately.

This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP POST request. Install body-parser using NPM as shown below.

npm install body-parser --save

Upvotes: 1

Related Questions