1

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
{}
Community
  • 1
  • 1
rawsh
  • 395
  • 5
  • 21

2 Answers2

5

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

Rohit Shedage
  • 23,944
  • 1
  • 13
  • 18
2

To extend the other answer, which is correct, body-parser checks the Content-Type before trying to parse the HTTP body.

If you'd like to change this behavior, you can have body-parser attempt to parse any input into json regardless of the Content-Type:

app.use(bodyParser.json({ type: '*' }));

The wildcard * will tell it to try to parse on any type: https://github.com/expressjs/body-parser#bodyparserjsonoptions

Sanketh Katta
  • 5,961
  • 2
  • 29
  • 30