How to consume JSON POST data in an Express application

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

        id = 1;
        name = foo;
        id = 2;
        name = bar;

On the server I have this.'/', function(request, response) {

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

    response.on('data', function(chunk) {

    response.on('end', function(){

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

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());'/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back


Test along the lines of:

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

For Express v4+

install body-parser from the npm.

$ npm install body-parser

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

var app = express()

// parse application/json

app.use(function (req, res, next) {
  console.log(req.body) // populated!