What is body parser in node.js?
Body Parser is a middleware of Node JS. it is used to handle HTTP POST request. Body Parser can parse string based client request body into JavaScript Object.
File Name :
npm install body-parser
include body-parser in our application, use following code.
File Name :
var bodyParser = require('body-parser');
req.body
req.body contains data ( in key-value form ) submitted in request body. The default value is undefined.
File Name :
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.
File Name :
<form method="post" action="127.0.0.01:3000/formdata">
<input type="text" name="username" required>
<input type="password" name="userpass" required>
<button>Send</button>
<form>
File Name :
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);
});
File Name :
var loginDetails = {
username : request.body.username,
password : request.body.password
};
bodyParser([options])
Returns middleware that parses both json and urlencoded. The options are passed to both middleware.
body-parser to do the same thing. body-parser used to be part of express. body-parser specifically for POST Requests object and PUT Requests object.
File Name :
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: true }));
bodyParser.json([options])
File Name :
Returns middleware that only parses json. The options are:
strict - only parse objects and arrays
limit <1mb> - maximum request body size
reviver - passed to JSON.parse()
bodyParser.urlencoded([options])
File Name :
Returns middleware that only parses urlencoded with the qs module. The options are:
limit <1mb> - maximum request body size
what is the difference between express.urlencoded({extended: false}) and express.json()
File Name :
If you use express.json() it will parse the body from post/fetch request except from html post form. It wont parse information from the html post form :
<form action="/" method="POST">
<input type="text" name="username">
<button>Submit</button>
</form>
For instance, if you fill the form with "dean_ilham" then submit it, Express wont have an idea what inside the body with this express code:
const express = require('express')
const app = express()
app.use(express.json())
// app.use(express.urlencoded({ extended: false }))
app.use(express.static("public"))
app.get("/", (req, res) => {
res.sendFile("index.html")
})
app.post("/", (req, res) => {
res.send(req.body)
})
const port = process.env.PORT || 3001
app.listen(port, () => {
console.log(`Server Up in Port ${port}`);
})
It will send {} after you click submit. But if you uncommented app.use(express.urlencoded({extended: false})), then you will get {"username": "dean_ilham"}.
So the difference is express.json() is a body parser for post request except html post form and express.urlencoded({extended: false}) is a body parser for html post form.
Previous
Next