NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
What is Body Parser in NodeJs?
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.
File Name :
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.