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.
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.
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}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With