Open In App

How to access Raw Body of a Post Request in Express.js ?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Raw Body of a POST request refers to unprocessed or uninterpreted data sent in the request before Express or any middleware processes or understands it. It’s like raw ingredients before the cooking begins.

In this article we will see various approaches to access raw body of a post request in Express.js.

Steps to Create Application:

1) Initialize a New Node.js Project:

Open your terminal or command prompt and navigate to the desired directory for your project. Then, run the following command to create a new Node.js project:

npm init -y

2) Install Express.js:

npm install express

3) Set Up the Express Application

To establish the entry point for your Express.js application, begin by creating a new JavaScript file in your project directory naming it for example app.js. In this file, import the Express.js module

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

Project Structure:

Screenshot-2024-03-09-124601

Dependencies in package.json:

 "dependencies": {
"express": "^4.18.3"
}

Let’s explore practical examples that illustrate each of the three approaches for accessing the raw body of a POST request in Express.js.

Note: To obtain the desired output, open postman and send a POST request. Populate the request body with a simple text, then proceed to send the POST request. This action should result in the expected output.

Using express.raw() Middleware

In modern versions of Express (4.16.0 and higher), developers can utilize the express.raw() middleware to seamlessly access the raw body of a POST request. Notably, this middleware efficiently parses the request body as a Buffer, offering a straightforward and effective method for handling raw data in your Express.js applications.

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

// Set the encoding for express.raw() 
app.use(express.raw({ type: '*/*', limit: '10mb' }));

app.post('/modern', (req, res) => {
  const rawBody = req.body;
  console.log('Modern Approach:', rawBody.toString('utf-8'));
  res.send(`How to access raw body of a POST request
              in Express.js? Modern Approach Received: ` 
            + rawBody.toString('utf-8'));
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

Output:

Screenshot-2024-03-10-154107

Using body-parser Middleware

In the earlier days of Express.js, developers commonly relied on the body-parser middleware as the primary tool for parsing raw request bodies. Utilizing body-parser.text() was the standard practice to manage the raw data efficiently. However, it’s essential to note that this approach has become outdated with the evolution of Express.js.

Install body-parser module before implementing this approach:

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

const app = express();
app.use(bodyParser.text());

app.post('/deprecated', (req, res) => {
  const rawBody = req.body;
  console.log('Deprecated Approach:', rawBody);
  res.send(`How to access raw body of a POST
              request in Express.js? Deprecated Approach Received: ` 
            + rawBody);
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

Output:

Screenshot-2024-03-10-152519

Using data and end Events

For those who prefer a more hands-on approach, manual handling of the data and end events offers a level of control over the raw body. This method involves accumulating chunks of data as they arrive and processing them when the request ends. Here’s a glimpse into how this approach can be implemented:

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

// Manual Handling: Using data and end events
app.post('/manual', (req, res) => {
  let rawBody = '';

  req.on('data', (chunk) => {
    rawBody += chunk;
  });

  req.on('end', () => {
    console.log('Manual Handling:', rawBody);
    res.send(`How to access raw body of a
              POST request in Express.js? Manual Handling Received: ` 
              + rawBody);
  });
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

Output:

Screenshot-2024-03-10-160351



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads