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

express, node.js, request

Solution

You need to pass a `Content-Type` to tell `bodyParser()` which parser to use. For regular form data, you should use `Content-Type: application/x-www-form-urlencoded`, so:

var options = {
  host: '127.0.0.1',
  port: 3000,
  path: '/api/users',
  method: 'POST',
  'Content-Type': 'application/x-www-form-urlencoded'
};

Should do the trick.

Edit: If you find yourself doing a lot of client HTTP requests in node, I heartily recommend Mikeal Rogers' `request` module, which makes these things a breeze.

Problem

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.

Original source