req.rawBody is no longer available (regression #34)
Problem
req.rawBody is no longer available in 1.5.1, I think it was the new "formidable" integration in connect/bodyParser that removed the feature. Is there another way to get the raw content after bodyParser parses the body?
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Restore req.rawBody Access in Express 1.5.1
In version 1.5.1 of Express, the integration of 'formidable' with connect/bodyParser has changed how request bodies are handled. The previous method of accessing raw body content via req.rawBody is no longer available as the body parser now processes the body before it can be accessed directly.
Awaiting Verification
Be the first to verify this fix
- 1
Install body-parser
If not already installed, add the 'body-parser' middleware to your project. This will allow you to parse the body of incoming requests while still retaining access to the raw body content.
bashnpm install body-parser - 2
Configure body-parser to retain raw body
Set up the body-parser middleware to parse the body and also retain the raw body content by using a custom middleware function.
javascriptconst bodyParser = require('body-parser'); app.use((req, res, next) => { req.rawBody = ''; req.on('data', chunk => { req.rawBody += chunk; }); req.on('end', next); }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); - 3
Access rawBody in route handlers
In your route handlers, you can now access req.rawBody to get the raw content of the request body after it has been parsed.
javascriptapp.post('/your-endpoint', (req, res) => { console.log(req.rawBody); // Access the raw body content res.send('Received'); }); - 4
Test the implementation
Send a test request to your endpoint and verify that req.rawBody contains the expected raw content of the request body.
bashcurl -X POST -d 'test data' http://localhost:3000/your-endpoint
Validation
To confirm the fix worked, send a POST request to your endpoint and check the server logs to ensure that req.rawBody contains the raw request body data as expected.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep