How to use body-parser Middleware In Express
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
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:
How to access Raw Body of a Post Request in Express.js ?
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.
Table of Content
- Using express.raw() Middleware
- Using body-parser Middleware
- Using data and end Events
Contact Us