Robert Robert - 5 months ago 9
Node.js Question

Node.js req.body is blank

I have tried the threads on Node "req is not defined" and req.body is empty when making a post request via http.request and similar, but the problem remains.

The server side code:

var express = require('express');
var bodyParser = require('body-parser');
var validator = require('validator');
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});

app.post('/sampleurl', function (req, res) {
var reqbody = req.body;
console.log(reqbody);
});

app.listen(process.env.PORT);
console.log("listening");


What I send (using hurl.it):

post request
response

What I get back from the server (the console.log):

listening
{}

Answer

I just tried your code.. It is perfectly fine..

What you are missing is adding headers in request.

Add Content-Type header as application/jsonenter image description here

Comments