The Wayback Machine - https://web.archive.org/web/20240906122651/https://www.geeksforgeeks.org/body-parser-middleware-in-node-js/
Open In App

Body-parser Middleware in Node.js

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. It’s commonly used in web applications built with Express.js to handle form submissions, JSON payloads, and other types of request bodies.

What is Body-parser?

body-parser is essential for handling incoming data in a variety of formats, such as JSON, URL-encoded form data, and raw or text data. It transforms this data into a readable format under req.body for easier processing in your application.

Features

  • Handles different types of request payloads, including JSON, URL-encoded, raw, and text data.
  • Simplifies the process of accessing request data, making it readily available under req.body.
  • Works seamlessly with Express.js and other Node.js frameworks.

Steps to Setup a body-parser Module

Step 1: First init the node app using the below command.

npm init -y

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

npm install body-parser express ejs

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

npm version body-parser

Project Structure:

0

Project Structure


The updated dependencies in your package.json file will look like this:

"dependencies":{
"body-parser": "^1.20.2",
"express": "^4.18.2",
"ejs": "^3.1.9"
}

Example: This code uses body-parser middleware in an Express.js application to parse URL-encoded and JSON request bodies, allowing access to form data via req.body.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Body-Parser Module Demo</title>
</head>

<body>
    <h1>Demo Form</h1>

    <form action="saveData" method="POST">
        <pre>
            Enter your Email : <input type="text"
                                      name="email"> <br>
                                
            <input type="submit" value="Submit Form">
        </pre>
    </form>
</body>
</html>
JavaScript
// Filename - index.js

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.use(bodyparser.json())

app.get("/", function (req, res) {
    res.render("SampleForm")
});

app.post('/saveData', (req, res) => {
    console.log("Using Body-parser: ", req.body.email)
})

app.listen(PORT, function (error) {
    if (error) throw error
    console.log("Server created Successfully on PORT", PORT)
})

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:

http://localhost:3000/

Demo Form

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

output

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

error

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

Summary

body-parser is a powerful middleware in Node.js used for parsing incoming request bodies. Whether you’re working with JSON, form data, or other content types, body-parser simplifies the process of accessing and handling this data. It is often used with express and is a core part of express which makes it easier to implement.



Similar Reads

Purpose of body-parser Middleware in Express
Express middleware acts like a toolbox for your web server, enabling you to customize how it manages requests and responses. It's a handy set of tools, that enhances Express's flexibility for specific tasks and gives you control over your server's capabilities Purpose of the body-parser Middleware in Express:Data Handling: body-parser is a middlewa
1 min read
What is the purpose of the cookie-parser middleware in Express.js?
cookie-parser is middleware that simplifies handling cookies. It parses incoming cookies from client requests and makes them accessible in the req.cookies object. This makes it easier to read and manipulate cookies in your Express JS application without manual parsing. Purpose of the cookie-parser middleware in ExpressJS:Cookie Parsing: Automatical
2 min read
Middleware in NestJS: Implementing Custom Middleware for Request Processing.
Middleware in NestJS plays an important role in intercepting and processing HTTP requests before they reach route handlers. It allows developers to execute code logic before or after handling a request, making it a powerful tool for managing cross-cutting concerns such as logging, authentication, error handling, and more. In this article, we will e
3 min read
Parsing form data in express app manually without body-parser
Parsing means accessing the data submitted by user with HTML form. When the form is submitted with the 'GET' method, data are appended in 'query string' and can access easily but when a form is submitted using the 'POST' method, it is somewhat difficult to get access over those data since they are encoded because of security purpose. There exist a
4 min read
Implementing Csurf Middleware in Node.js
Csurf middleware in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSRF token as a cookie. The token sent will be differ
4 min read
Understanding Mongoose Middleware in Node.js
A Mongoose is a powerful tool for NodeJS developers working with MongoDB databases. It simplifies database interaction, allowing developers to focus more on building their applications. In this article, we'll cover the basics of Mongoose, including how to connect to a MongoDB database and perform CRUD operations. We'll also explore Mongoose middlew
5 min read
How to Build Middleware for Node JS: A Complete Guide
NodeJS is a powerful tool that is used for building high-performance web applications. It is used as a JavaScript on runtime environment at the server side. One of Its key features is middleware, which allows you to enhance the request and response object in your application. Building middleware for Node.js involves creating custom functions to pro
5 min read
API Response Caching using apicache Middleware in Node.js
APIs are a crucial part of modern web applications, providing the means for different software systems to communicate and exchange data. However, frequent API calls, especially to the same endpoints, can lead to increased server load, slower response times, and higher bandwidth usage. Caching is a strategy to mitigate these issues by storing copies
4 min read
Moment.js Java DateFormat Parser Plugin
Moment.js is a JavaScript library that helps parse, validate, manipulate, and display date/time in JavaScript in a very easy way. It also allows displaying of dates as per localization and in a human-readable format. Java DateFormat Parser Plugin: The Java DateFormat Parser Plugin is used to translate any date provided by the user into the format s
3 min read
Express Cookie-Parser - Signed and Unsigned Cookies
A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using. With the help of cookies - It is easy for websites to remember the user's information It is easy to capture the user's browsing history It is also useful in storing the user's sessions Th
5 min read
JavaScript JSON Parser
JSON (JavaScript Object Notation) is a popular lightweight data exchange format for sending data between a server and a client, or across various systems. JSON data is parsed and interpreted using a software component or library called a JSON parser. Through the JSON parsing process, a JSON string is converted into a structured format that is easy
3 min read
HTML Entity Parser
Given a string str which has various HTML Entities in it, the task is to replace these entities with their corresponding special character. HTML entity parser is the parser that takes HTML code as input and replaces all the entities of the special characters by the characters itself. The special characters and their entities for HTML are Quotation
15+ min read
Working of Express.js middleware and its benefits
Framework: It is known to be a skeleton where the application defines the content of the operation by filling out the skeleton. For Web development, there is python with Django, java with spring, and For Web development in we have Node.js with Express.js in node.js there is an HTTP module by which we can create only limited operatable websites or w
7 min read
How to pass variables to the next middleware using next() in Express.js ?
The following example covers how to pass variables to the next middleware using next() in Express.js. Approach: We cannot directly pass data to the next middleware, but we can send data through the request object. [Middleware 1] [Middleware 2] request.mydata = someData; -------&gt; let dataFromMiddleware1 = request.mydata; Installation of Express m
2 min read
How to create custom middleware in express ?
Express.js is the most powerful framework of the node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. Express.js use different kinds of middleware functions in order to complete the different requests made by the client for e.g. client can m
2 min read
How to skip a middleware in Express.js ?
If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call. Prerequisite: express.js: To handle routing. Setting up environment and execution: Step 1: Initialize node project npm init Step 2: Install required modules npm install expre
1 min read
What is Middleware in Express.js ?
Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middleware. The next() function is used to call the next m
2 min read
How to return an error back to ExpressJS from middleware ?
In this article, we are going to cover the problem of "How to return errors/exceptions to ExpressJS using middleware". Error handling refers to catching and processing errors that might occur both synchronously and asynchronously. Fortunately, ExpressJS comes with its own error handler, so you don't need to write your own. Middleware functions have
2 min read
Express Error Handling - Middleware for Production and Development
Error handling is the process of detecting and responding to errors that occur during the execution of a program or application. In the context of web applications, error handling typically involves detecting errors that occur during the handling of HTTP requests and responding appropriately to those errors. Effective error handling is important be
4 min read
Difference between app-level and route-level middleware in Express
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next middleware function in the application's request-response cycle. In this article, we will go through app-level and route-level middleware and also see the key differences between them. Table of Content What is App-level Middl
3 min read
Difference between application level and router level middleware in Express?
If you’ve used Express even a little, you know how important middleware is. Those little functions run on every request and let you do stuff like logging, authentication, file uploads, and more. In this article, we will see what is Application-level middleware and Router-level middleware and what are the key differences between them. Table of Conte
3 min read
Purpose of middleware in Express
Middleware in Express is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly it's work is to make the Express framework more powerful and flexible. It allows users to insert additional steps or actions in the process of handling a request and generating a response. It's
2 min read
Purpose of the express.Router middleware in Express
express.Router() in ExpressJS is like creating a mini-app within your main app. It helps organize routes and related functionalities, making it easier to manage different parts of your web application separately. express.Router() acts as a path organizer in ExpressJS, helping to structure and manage routes efficiently within a web application. Purp
1 min read
Explain the concept of middleware in NodeJS
Middleware in NodeJS refers to a software design pattern where functions are invoked sequentially in a pipeline to handle requests and responses in web applications. It acts as an intermediary layer between the client and the server, allowing for modularization of request processing logic and enabling cross-cutting concerns such as authentication,
2 min read
Common middleware libraries used in Redux
Middleware libraries play a crucial role in Redux applications, enabling users to extend and enhance Redux's capabilities. The middleware libraries offer a wide range of capabilities and cater to different use cases and preferences. users can choose the middleware that best fits their requirements and development style to enhance their Redux applic
5 min read
What is Logger middleware in React Redux ?
Logger middleware is a tool that helps users understand what's happening behind the scenes in their Redux-powered React applications. It logs information about each action that gets dispatched in your app, along with the state before and after the action is processed. Syntax:import { createStore, applyMiddleware } from 'redux';import logger from 'r
3 min read
Explain the purpose of the helmet middleware in Express JS
Helmet is a security middleware for ExpressJS applications. It helps protect your web application from common security vulnerabilities by setting HTTP headers that enhance security. By using Helmet, you can easily add an extra layer of protection to your ExpressJS application without needing to manually configure each security header. Purpose of th
2 min read
What is the purpose of the compression middleware in Express JS ?
Middleware in Express JS is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly it’s work is to make the ExpressJS framework more powerful and flexible. It allows users to insert additional steps or actions in the process of handling a request and generating a response.
2 min read
Explain the purpose of the express.static middleware in Express JS
The express.static middleware in ExpressJS simplifies serving static files like HTML, CSS, and images, improving performance and enhancing user experience in web applications. Purpose of the express.static middleware in ExpressJS:Serves Static Files: express.static middleware serves static files like HTML, CSS, JavaScript, and images from a specifi
2 min read
What is the purpose of the express-validator middleware in Express JS?
The express-validator middleware is a powerful tool for validating and sanitizing incoming request data in ExpressJS applications. It helps ensure that user input meets specified criteria, preventing security vulnerabilities and data corruption. With built-in error handling and customizable rules, express-validator seamlessly integrates with Expres
2 min read