Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 206
Sree.Bh Avatar asked Apr 03 '16 17:04

Sree.Bh


People also ask

What happens if you don't use body parser?

You will just lose the data, and request. body field will be empty. Though the data is still sent to you, so it is transferred to the server, but you have not processed it so you won't have access to the data.

What is JSON body parser?

Express body-parser is an npm module used to process data sent in an HTTP request body. It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets over an HTTP request body. Before the target controller receives an incoming request, these middleware routines handle it.

Which method will you use in your Express application to get JSON data from the client side?

The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.

How do you use a body parser?

To use the Text body parser, we have to write app. use(bodyParser. text()) and the Content-Type in your fetch API would be text/html . That's it, now your backend service will accept POST request with text in the request body.


2 Answers

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);
like image 127
alexmac Avatar answered Oct 06 '22 00:10

alexmac


Change the request header

'Content-Type':'application/json'

So that bodyParser can parse the body.

*That is what works for me. i am using angular 2+ with express(body-parser)

like image 30
bereket gebredingle Avatar answered Oct 05 '22 22:10

bereket gebredingle