How to exclude JSON from incoming request body in node.js server

Problem

I wanna send JSON data in request body of POST method to a server which will be written in node.js . I've tried a code like;

var http = require('http');
http.createServer(function (req, res) {
    console.log(req.body)
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

and I've tested it with curl as;

curl -i -v -X POST -d '{"a":5}' http://127.0.0.1:1337 -H "content-type:application/json"

But it says body is undefined.

Is there a way to get JSON data from request?

Thank!

Problem courtesy of: Ahmet DAL

Solution

Node.js is pretty low-level out of the box. Either you have to capture the request body yourself, or use something like connect.

DIY:

var http = require('http');
http.createServer(function (req, res) {
    var body = '';
    req.on('data', function(data) {
        body += data;
    });
    req.on('end', function() {
        console.log(body);
    });
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Connect:

var connect = require('connect');
connect()
    .use(connect.bodyParser())
    .use(function(req, res) {
        console.log(req.body);
    })
   .listen(3000);
Solution courtesy of: Linus Gustav Larsson Thiel

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.