Middleware for parsing JSON request bodies. Only parses requests where the Content-Type header matches the type option and supports automatic inflation of compressed bodies.
Creates middleware that parses JSON bodies and populates req.body with the parsed data.
/**
* Create middleware to parse JSON bodies
* @param {object} [options] - Configuration options
* @returns {function} Express middleware function
*/
function json(options?: {
inflate?: boolean;
limit?: number | string;
reviver?: (key: string, value: any) => any;
strict?: boolean;
type?: string | string[] | ((req: IncomingMessage) => boolean);
verify?: (req: IncomingMessage, res: ServerResponse, buf: Buffer, encoding: string) => void;
}): (req: IncomingMessage, res: ServerResponse, next: (err?: any) => void) => void;booleantruetrue, deflated (compressed) bodies will be inflated; when false, deflated bodies are rejectednumber | string'100kb'functionundefinedJSON.parse as the second argument for custom JSON parsingbooleantruetrue, only accepts arrays and objects; when false, accepts anything JSON.parse acceptsstring | string[] | function'application/json'functionundefinedverify(req, res, buf, encoding) where buf is the raw request body Buffer. Can abort parsing by throwing an errorBasic JSON parsing:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
// Parse JSON with default options
app.use(bodyParser.json());
app.post('/api/users', (req, res) => {
console.log(req.body); // { name: "John", age: 30 }
res.json({ received: req.body });
});Custom options:
app.use(bodyParser.json({
limit: '50mb',
strict: false,
type: 'application/*',
verify: (req, res, buf, encoding) => {
// Custom verification logic
if (buf.length === 0) {
throw new Error('Empty body not allowed');
}
}
}));With reviver function:
app.use(bodyParser.json({
reviver: (key, value) => {
// Convert date strings to Date objects
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
return new Date(value);
}
return value;
}
}));Custom type checking:
app.use(bodyParser.json({
type: (req) => {
return req.headers['content-type'] === 'application/vnd.api+json';
}
}));The JSON parser can throw several types of errors:
app.use(bodyParser.json());
app.use((err, req, res, next) => {
if (err.type === 'entity.parse.failed') {
return res.status(400).send('Invalid JSON');
}
if (err.type === 'entity.too.large') {
return res.status(413).send('JSON too large');
}
next(err);
});