- When building a backend application with express, handling a incoming request data is common.
- One of the most frequently used type of data is JSON.
- This is where express comes to play.
express.json() reads JSON data in the incoming request body and converts into Javascript Object that can easily access in route handlers.
Why Do We Need express.json()?
HTTP requests often send data in the body, especially in POST requests. Without parsing, Express doesn’t automatically understand JSON format.
For example:
{
"name": "Vasanth",
"email": "vasanth@example.com"
}
If try to access req.body without using express.json(), it will be undefined.
app.post('/users', (req, res) => {
console.log(req.body.name); // Works only if express.json() is used
res.send('User received');
});
How to Use express.json()
const express = require('express');
const app = express();
// Middleware to parse JSON data
app.use(express.json());
app.post('/users', (req, res) => {
const user = req.body;
res.send(`User ${user.name} with email ${user.email} added successfully!`);
});
app.listen(8000, () => {
console.log('Server running on port 8000');
});
Top comments (0)