Express req.body Property
What you’ll learn
- How
req.bodyis populated by Express middleware. - How to parse JSON and form payloads correctly.
- Why parser order and Content-Type matter.
- How to validate request body data safely.
Usage syntax
javascript
req.body1
Read JSON payload using express.json()
javascript
app.use(express.json());
app.post('/users', function (req, res) {
var name = req.body.name;
if (!name) return res.status(400).json({ error: 'name is required' });
res.status(201).json({ message: 'User created', name: name });
});2
Parse form data with urlencoded middleware
javascript
app.use(express.urlencoded({ extended: true }));
app.post('/contact', function (req, res) {
var email = req.body.email;
res.send('Thanks, ' + email);
});❓ FAQ
It contains parsed request payload data sent by the client, such as JSON or form fields.
Most often because body parser middleware is missing, misordered, or Content-Type does not match parser expectations.
Use app.use(express.json()) before your routes to parse application/json payloads.
Use app.use(express.urlencoded({ extended: true })) for application/x-www-form-urlencoded data.
No. Always validate and sanitize input before using it in business logic or database operations.
Did you know?
req.body is populated only after body-parsing middleware like express.json() or express.urlencoded() runs.
4 people found this page helpful
