Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 325
Louis Grellet Avatar asked Aug 20 '12 14:08

Louis Grellet


2 Answers

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.

like image 195
Linus Thiel Avatar answered Oct 02 '22 01:10

Linus Thiel


Ensure these lines are present in your app.js or server.js

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
like image 31
suku Avatar answered Oct 01 '22 23:10

suku