Shane
Shane

Reputation: 5161

Express + bodyParser.json() + Postman, req.body is empty

When using the following:

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

app.post('/test', bodyParser.json(), function(req, res) {
  res.json(req.body);
});

var port = 4040;
app.listen(port, function() {
  console.log('server up and running at port: %s', port);
});

and the following post from Postman:

enter image description here

I get an empty response. I've followed a lot of threads on using bodyParser.json() and for some reason I'm still receiving an empty object in response. What am I missing?

Upvotes: 0

Views: 5602

Answers (2)

dizballanze
dizballanze

Reputation: 1267

To make bodyParser.json works you should provide Content-Type header with value application/json in your requests.

Upvotes: 7

gnerkus
gnerkus

Reputation: 12047

A safer way to use body-parser would be to apply it as middleware for the entire app. The code will have to be refactored in this manner:

// Permit the app to parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// Use body-parser as middleware for the app.
app.use(bodyParser.json());

app.post('/test', function(req, res) {
  res.json(req.body);
});

When you make a request on Postman, make sure to select the x-www-form-urlencoded tab as opposed to the raw tab.

Upvotes: 5

Related Questions