Resolving ‘Body-Parser Deprecated’ Error in Express.js

In this article, we are going to solve the “body-parser deprecated” error that occurs during the use of bodyParser package in Express, specifically in versions above 4.16.0. We will do a detailed study on why it happens and how to fix it.

Let’s start with the introduction of Express.js and body-parser and see how to use body-parser in Express version less than 4.16.0.

Also Read: Resolving “Cannot find module” Error in Node.js

Understanding Express and body-parser

Express.js is widely used in the Node.js ecosystem. It is used to build web applications and APIs. It is very simple, flexible and easy to use.

On the other hand, bodyParser is a package in Node.js that is used to simplify the process of parsing request bodies in various formats. It works with Express to make it easier to work with incoming data in Node applications.

Using body-parser in Express version less than 4.16.0

For Express version less than 4.16.0, we can use the body-parser package in the following way to parse the body of incoming HTTP request

First, we need to install the body-parser package using npm or yarn:

npm install body-parser
# or
yarn add body-parser

Once the package is installed, we can use it in your Node.js application to parse the request body.

Below is a simple example of how to use body-parser with Express.js to parse JSON and URL-encoded request bodies:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

// Parse JSON request bodies
app.use(bodyParser.json());

// Parse URL-encoded request bodies
app.use(bodyParser.urlencoded({ extended: true }));

// Define a route that handles POST requests
app.post('/api/data', (req, res) => {
  // Access the parsed data from the request body
  const jsonData = req.body;

  // Process the data or respond as needed
  res.json({ message: 'Data received successfully', data: jsonData });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Explanation of the above code:

  1. We import the ‘express’ and ‘body-parser’ modules.
  2. We create an Express instance ‘app’ and set it up to use body-parser for JSON and URL-encoded request bodies.
  3. We define a route that listens for POST requests at /api/data.
  4. Inside the POST route handler, we access the parsed request body using the req.body and can then process or respond to the data as needed.
  5. Finally, we use the listen() method to run the application on port 3000 & log a success message to the console.

Resolving ‘Body-Parser Deprecated’ Error

Now after knowing some basics let’s drive deeper into the problem of why sometimes the error comes while using the body-parser package that is ‘body-parser is deprecated express 4’.

In Express.js version 4.16.0 or later the ‘body-parser’ middleware has been deprecated and is no longer necessary because it has been integrated into the Express core under the express.urlencoded() and express.json() middleware.

express.json()

The express.json() is used to parse the JSON (JavaScript Object Notation) data sent in the request body.

To use express.json(), we typically include it as middleware in our Express application. This middleware should be used before the routes that need to access the JSON data.

const express = require('express');
const app = express();

// Middleware to parse JSON request bodies
app.use(express.json());

// route handling code here

When a request comes to the Express server with a JSON body, express.json() automatically parses the JSON data and attaches it to the req.body property.

app.post('/api/data', (req, res) => {
  const jsonData = req.body; // Access the parsed JSON data here
  //code to process the JSON data
});

The client must include the Content-Type: application/json header in the HTTP request. express.json() will only parse the body as JSON if this header is set.

POST /api/data
Content-Type: application/json

{
  "key": "value"
}

express.urlencoded()

The express.urlencoded is used to parse the URL-encoded data sent in the request body

To use express.urlencoded(), we typically include it as middleware in our Express application. This middleware should be used before the routes that need to access the JSON data.

const express = require('express');
const app = express();

// Middleware to parse URL-encoded request bodies
app.use(express.urlencoded({ extended: true }));

//route handling code here

When a request comes to the Express server with a URL-encoded data body, express.urlencoded() automatically parses that data and attaches it to the req.body property.

app.post('/api/data', (req, res) => {
  const formData = req.body; // Access the parsed URL-encoded data here
  // Your code to process the form data
});

The client must include the Content-Type: application/x-www-form-urlencoded header in the HTTP request. express.urlencoded() will only parse the body as URL-encoded data if this header is set.

POST /api/data
Content-Type: application/x-www-form-urlencoded

key1=value1&key2=value2

Solution

There is no longer a need to separately install and use the body-parser package in Express.js 4.16 and later versions. The functionalities of the body-parser package are incorporated in the built-in middleware in Express, i.e., express.urlencoded() and express.json() middleware. So just use these middlewares in the process of parsing request bodies in your Express applications.

Conclusion

Now we have reached to the end of this article. Hope it has elaborated on the problem ‘bodyParser is deprecated express 4‘. In Express version 4.16.0 and later the ‘body-parser’ middleware has been deprecated. Express.js now provides built-in middleware functions express.urlencoded() and express.json() to handle URL-encoded and JSON request bodies, respectively. These built-in middlewares make it easier and more efficient to parse and work with request data in Express applications without the need for an external package like body-parser. For more such articles on Node and Express follow https://codeforgeek.com/.

References

Arnab Biswas
Arnab Biswas
Articles: 10