Express JS body-parser
body-parser
is a middleware in Express.js that parses incoming request bodies and makes the data available under the req.body
property. It is commonly used when handling POST or PUT requests, where the data is sent as part of the request body.
Key Features of body-parser
:
Parses JSON and URL-encoded data:
body-parser
can handle two main content types:application/json
: Parses JSON data.application/x-www-form-urlencoded
: Parses data encoded in the query string format (usually from HTML form submissions).
Accessing Parsed Data:
- Once the middleware is applied, you can access the parsed data using
req.body
.
- Once the middleware is applied, you can access the parsed data using
Installation:
- Although
body-parser
used to be a separate module, it's now included in Express.js as a built-in middleware. So, you don't have to install it separately.
npm install express
- Although
Usage Example:
Here’s a simple usage of body-parser
in an Express.js application:
const express = require('express');
const app = express();
// For parsing application/json
app.use(express.json());
// For parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
app.post('/submit', (req, res) => {
console.log(req.body); // Logs the parsed request body
res.send('Data received');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Explanation of extended
Option:
extended: true
: Allows parsing of richer data structures like arrays and nested objects.extended: false
: Supports simple key-value pairs (the default isfalse
).
Common Use Cases:
- Handling form submissions: When users submit forms with POST requests,
body-parser
helps extract and parse the submitted data. - Processing JSON API requests: For applications that send and receive JSON data,
body-parser
helps easily parse the incoming JSON data.
Now, since Express 4.16.0, body-parser
is included in Express as express.json()
and express.urlencoded()
. So for new Express applications, you don’t need to install body-parser
separately unless you need to configure additional custom parsing logic.