How to use express.raw() Middleware In Express
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.
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:
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