Lesson 12 / 23
Parsing & Sending JSON
express.json() in, res.json() out.
Parsing an incoming body
Without express.json(), req.body is undefined. With it, a JSON payload becomes a plain object.
app.use(express.json());
app.post('/items', (req, res) => {
const { name, price } = req.body;
res.status(201).json({ name, price, id: Date.now() });
});Sending JSON back
res.json(obj) stringifies obj and sets Content-Type: application/json automatically.
app.get('/health', (req, res) => {
res.json({ status: 'ok', uptime: process.uptime() });
});Content-Type must match
express.json() only parses requests sent with Content-Type: application/json — otherwise req.body stays empty.