Body Parser
Written By: Avinash Malhotra
Updated on
What is Body Parser?
Body Parser is a middleware of Node JS used to handle HTTP POST request. Body Parser can parse string based client request body into JavaScript Object which we can use in our application.
What Body Parser Do?
- Parse the request body into JS Object ( if content-type is application/JSON) or a HTML Form data where MIME type is application/x-www-form-urlencoded.
- Put above JS Object in req.body so that middleware can use the data.
Install Body Parser
npm i body-parser
Body Parser middleware was earlier a part of express js. For Express 4.16 and above, we have to install it separately.
API
To include body-parser in our application, use following code. The bodyParser object has two methods, bodyParser.json() and bodyParser.urlencoded(). The data will be available in req.body property.
var bodyParser = require('body-parser');
req.body
req.body contains data ( in key-value form ) submitted in request body. The default value is undefined.
req.json
const express=require('express');
const app=express();
const bodyParser=require('body-parser');
// parse application/json
app.use(bodyParser.json());
app.post('post',(req,res)=>{
console.log(req.body);
res.json(req.body);
});
Form Data
Use bodyParser to parse HTML Form Data received through HTTP POST method. Create a separate HTML Form with inputs. Use name attributes in all input controls. Set the method (in html form ) to POST and action to path of Post request.
const express=require('express');
const app=express();
const bodyParser=require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.post('formdata',(req,res)=>{
console.log(req.body);
res.json(req.body);
});
HTML Page
<form method="post" action="/login">
<input type="text" name="name" required>
<input type="password" name="pass" required>
<button>Send</button>
<form>