Open In App

Body-parser middleware in Node.js

Last Updated : 03 Apr, 2023
Like Article

Body-parser is the Node.js body-parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. 

Installation of body-parser module:

You can visit the link to Install the body-parser module. You can install this package by using this command.

npm install body-parser

After installing body-parser you can check your body-parser version in the command prompt using the command.

npm version body-parser

After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.

node index.js

Project Structure:

project structure


SampleForm.ejs: The below code should be in the SampleForm.ejs


<!DOCTYPE html>
    <title>Body-Parser Module Demo</title>
    <h1>Demo Form</h1>
    <form action="saveData" method="POST">
            Enter your Email : <input type="text"
                                      name="email"> <br>
            <input type="submit" value="Submit Form">



const bodyparser = require('body-parser')
const express = require("express")
const path = require('path')
const app = express()
let PORT = process.env.port || 3000
// View Engine Setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
// Body-parser middleware
app.use(bodyparser.urlencoded({ extended: true }))
app.get("/", function (req, res) {
});'/saveData', (req, res) => {
    console.log("Using Body-parser: ",
app.listen(PORT, function (error) {
    if (error) throw error
    console.log("Server created Successfully on PORT", PORT)

Steps to run the program:

Make sure you have installed ‘view engine’ like I have used “ejs” and also installed express and body-parser module using the following commands:

npm install express
npm install ejs
npm install body-parser

Run the index.js file using the below command:

node index.js

Now Open the browser and type the below URL and you will see the Demo Form as shown below:


Demo Form

Now submit the form and then you will see the following output: 


But if we do not use this body-parser middle, then while parsing, an error will occur as shown below: 


So this is how you can use the body-parser module for parsing incoming request bodies in middleware before you handle it.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads