The JSON data in request body is not getting parsed using body-parser

Sree.Bh picture Sree.Bh · Apr 3, 2016 · Viewed 11.8k times · Source

When I send a POST request using postman to localhost:8080/api/newUser with request body:

{name: "Harry Potter"}

At server end console.log(req.body) prints:

{ '{name: "Harry Potter"}': '' }

server.js

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

app.use('/', express.static(__dirname));

router.use(function(req, res, next) {
    next();
});

router
    .route('/newUser')
    .post(function(req, res) {
        console.log(req.body);
    });

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.use('/api', router);

app.listen(8080);

What am I doing wrong?

Answer

alexmac picture alexmac · Apr 3, 2016

In express.js the order in which you declare middleware is very important. bodyParser middleware must be defined early than your own middleware (api endpoints).

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

app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies

router
    .route('/newUser')
    .post(function(req, res) {
        console.log(req.body);
    });

app.use('/api', router);

app.listen(8080);