What does body-parser do with express?
I don't understand why we need body-parser
in an Express application, as we can get data without using body-parser
.
And what does it do actually and how?
To handle HTTP POST
requests in Express.js version 4 and above, you need to install the middleware module called body-parser
.
body-parser
extracts the entire body portion of an incoming request stream and exposes it on req.body
.
The middleware was a part of Express.js earlier but now you have to install it separately.
This body-parser
module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST
request. Install body-parser
using NPM as shown below.
npm install body-parser --save
edit in 2019-april-2: in [email protected] the body-parser middleware bundled with express. for more details see this
Yes we can work without body-parser
. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.
Or you can use body-parser
, as the express team is maintaining it .
What body-parser can do for you: It simplifies the request.
How to use it: Here is example:
Install npm install body-parser --save
This how to use body-parser in express:
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Link.
https://github.com/expressjs/body-parser.
And then you can get body and headers in root request object . Example
app.post("/posturl",function(req,res,next){
console.log(req.body);
res.send("response");
});