What is Body-Parser?
Body-parser is a middleware in Node.js that helps handle incoming request bodies in Express applications. It parses incoming JSON, URL-encoded, and raw data from the client, making it accessible via req.body.
Why Do We Need Body-Parser?
By default, Express does not parse request bodies. If a client sends data in a POST or PUT request, it arrives as a stream, which is hard to handle manually. Body-parser makes it easy to extract and use this data.
How to Use Body-Parser in Express?
1. Install Body-Parser
Run the following command:
npm install body-parser2. Import and Use Body-Parser in Express
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// Middleware to parse JSON data
app.use(bodyParser.json());
// Middleware to parse URL-encoded data (for form submissions)
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/data', (req, res) => {
console.log(req.body); // Access parsed data
res.send('Data received!');
});
app.listen(3000, () => console.log('Server running on port 3000'));Types of Body-Parser Middleware
-
bodyParser.json()→ Parses incoming JSON data. -
bodyParser.urlencoded({ extended: true })→ Parses form data (application/x-www-form-urlencoded). -
bodyParser.raw()→ Parses raw body buffer (e.g.,application/octet-stream). -
bodyParser.text()→ Parses incoming text (text/plain).
Is Body-Parser Still Needed?
Since Express 4.16.0, express.json() and express.urlencoded() are built-in, so you don’t need to install body-parser separately. Instead, just use:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));Conclusion
Body-parser is an essential middleware for handling incoming request data in Express. While it's still widely used, modern Express versions include its functionality by default. 🚀