How do I consume the JSON POST data in an Express application

Go To StackoverFlow.com

242

I'm sending the following JSON string to my server.

(
        {
        id = 1;
        name = foo;
    },
        {
        id = 2;
        name = bar;
    }
)

On the server I have this.

app.post('/', function(request, response) {

    console.log("Got response: " + response.statusCode);

    response.on('data', function(chunk) {
        queryResponse+=chunk;
        console.log('data');
    });

    response.on('end', function(){
        console.log('end');
    });
});

When I send the string, it shows that I got a 200 response, but those other two methods never run. Why is that?

2012-04-04 06:27
by neuromancer


357

I think you're conflating the use of the response object with that of the request.

The response object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answer which provides some guidance.

If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParser middleware to parse the request body and place the result in request.body of your route.

var express = require('express')
  , app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back
});

app.listen(3000);

Test along the lines of:

$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}

Updated for Express 4+

Body parser was split out into it's own npm package after v4, requires a separate install npm install body-parser

var express = require('express')
  , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

Update for Express 4.16+

Starting with release 4.16.0, a new express.json() middleware is available.

var express = require('express');

var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);
2012-04-04 08:33
by Pero P.
How would I access "MyKey" to get "My Value" - neuromancer 2012-04-04 09:07
request.body.MyKeyPero P. 2012-04-04 09:10
How come it doesn't work for console.log("request = " + request.body) - neuromancer 2012-04-04 09:40
Because the concatenation invokes toString() on the object. Take a look at the node docs for console.log, as that inspects the object and returns a string representation - Pero P. 2012-04-04 10:15
I thought it was something like that. So how can I change it so it works - neuromancer 2012-04-04 10:26
console.log('request =' + JSON.stringify(request.body))Pero P. 2012-04-04 16:49
let us continue this discussion in chatneuromancer 2012-04-04 23:32
The current console.log() will automatically stringify an object (via util.inspect()), so this would work: console.log("with request", request.body);Tommy Stanton 2013-10-01 23:10
Hi i have the following issue: http://stackoverflow.com/questions/19917401/node-js-express-request-entity-too-large/ and the following code: http://codepen.io/mike-jam-es/pen/hHbwJ Express: 3.4.4 If someone could provide some help on this it would be very much appreciated thanks - mike james 2013-11-13 20:58
Could you updated this answer for Express v4+ - Keith Pinson 2014-06-13 20:32
This answer is outdated, but the one from @chrisarton is up to date - Emil Ingerslev 2016-01-11 09:30
Answer updated for Express v4 - Pero P. 2016-12-14 18:21
@pero can you please help me with this: https://github.com/expressjs/body-parser/issues/21 - codeinprogress 2016-12-21 15:14


192

For Express v4+

install body-parser from the npm.

$ npm install body-parser

https://www.npmjs.org/package/body-parser#installation

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next()
})
2014-07-08 15:05
by chrisarton
why do they keep taking out stuff everyone uses - light24bulbs 2014-10-17 04:30
@light24bulbs So it (Express) will be more lean and mean for those who don't use/need that - andyengle 2014-11-04 02:38
@andyengle That does make sense. But I think virtually everyone uses request parsing. That seems like a core feature to me - light24bulbs 2014-11-05 02:54
Since the middleware function interface is a standard used by many libraries, it also allows apps that don't use Express to use these middleware functions - Anm 2015-01-31 12:53
Taking it out of express doesn't allow it to be used by apps that do not use requests. They could have made it separate, and included it in express by default - J.J 2016-10-23 14:31
my body returns empty when data type is JSO - mrid 2017-10-04 06:25


10

Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:

        const res_data = JSON.parse(body);
2016-07-21 03:29
by xims
The original question is about parsing JSON from a POST message in the Express framework. Without the BodyParser middleware, the JSON data will not exist in the body property of the request object - ThisClark 2016-11-07 02:39
I found this useful, when parsing server response. Thanks - Hasan Alsawadi 2016-11-09 08:21
Thank you Hasan, I appreciate your comment. It did helped me when I was looking for solution and came across this post. Not sure if it works in all cases but it definitely works in some and it is a better solution than using third party library - xims 2016-11-11 00:48
Your answer and a comment provides the answer with more information (the more information being your answer here). You should update your answer to indicate that express needs the body-parser or give an alternative to indicate how body-parser got the data in the first place - dewwwald 2016-12-20 20:19
does not define bodyjameshfisher 2016-12-25 08:34
But where do I get the string body - Tomáš Zato 2017-09-25 22:31


1

For those getting an empty object in req.body

I had forgotten to set headers: {"Content-Type": "application/json"} in the request. Changing it solved the problem.

2019-01-10 03:10
by Daniel Thompson
Can't believe I missed this! I was sending with text/json and getting {} as a response. Total oversight on my part. Very helpful - James M. Lay 2019-01-24 01:03
Ads