## Setting Up JSON Body Parser in Express 4.x+
Modern Express applications include built-in JSON parsing middleware powered by `body-parser`. You don't need to install external packages.
Basic Setup Example
const express = require('express');// Enable JSON body parsing with 1MB limit app.use(express.json({ limit: '1mb' }));
app.post('/api/users', (req, res) => { const { name, email } = req.body; console.log('Received JSON:', name, email); res.status(201).json({ status: 'created', user: { name, email } }); });
app.listen(3000, () => console.log('Server running on port 3000')); ```
Catching Invalid JSON Syntax Errors
When a client sends broken JSON, Express throws a 400 SyntaxError. You can capture it cleanly with a global error handler:
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
return res.status(400).json({ error: 'Malformed JSON payload syntax.' });
}
next();
});--- Validate your Node.js API test payloads using our free JSON Validator!