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

Jsonnode.jsExpress

Json Problem Overview


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?

Json Solutions


Solution 1 - Json

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.

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);

Updated for Express 4.0 - 4.15

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);

For earlier versions of Express (< 4)

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"}

Solution 2 - Json

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()
})

Solution 3 - Json

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.

Solution 4 - Json

@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).

In my case I needed to force content-type: text/plain to be parsed as json.

If you cannot change the content-type of the request, try using the following code:

app.use(express.json({type: '*/*'}));

Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:

app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
  // echo json
  res.json(req.body);
});

Solution 5 - Json

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);

Solution 6 - Json

const express = require('express');
let app = express();
app.use(express.json());

This app.use(express.json) will now let you read the incoming post JSON object

Solution 7 - Json

A beginner's mistake...i was using app.use(express.json()); in a local module instead of the main file (entry point).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneuromancerView Question on Stackoverflow
Solution 1 - JsonPero P.View Answer on Stackoverflow
Solution 2 - JsonchrisartonView Answer on Stackoverflow
Solution 3 - JsonDaniel ThompsonView Answer on Stackoverflow
Solution 4 - JsonannebView Answer on Stackoverflow
Solution 5 - JsonximsView Answer on Stackoverflow
Solution 6 - JsonSuRaView Answer on Stackoverflow
Solution 7 - JsonHatimView Answer on Stackoverflow