req.body is empty when making a post request via http.request

Viewed 14728

I have a nodejs app using bodyparser(), and this route :

app.post('/users', function(req, res){
  res.json(req.body)
})

when i curl

curl -X POST 127.0.0.1:3000/users -d 'name=batman'

server sends back this json :

{ name: 'batman' }

my problem is when trying to make the same request with http.request, req.body is empty i'm doing the same call though, here is a test.js file that i run with node :

var http = require('http');

var options = {
  host: '127.0.0.1',
  port: 3000,
  path: '/api/users',
  method: 'POST'
};

var request = http.request(options, function (response) {
  var str = '';
  response.on('data', function (chunk) {
    str += chunk;
  });

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

request.end("name=batman");

request body is empty -> {}

why ? i've tried setting content-length but does not do anything.

2 Answers
Related