How to use data and end Events In Express
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:
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:
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