neuromancer neuromancer - 1 year ago 118
JSON Question

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?

Answer Source

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