### Install body-parser Source: https://github.com/expressjs/body-parser/blob/master/README.md Install the body-parser package using npm. ```sh $ npm install body-parser ``` -------------------------------- ### Example Usage of Body-Parser JSON Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/types.md Demonstrates how to instantiate the JSON parser with custom options for limit, strictness, and a reviver function. Ensure the 'body-parser' package is installed. ```typescript const jsonParser = bodyParser.json({ limit: '10mb', strict: false, reviver: (key, value) => value }) ``` -------------------------------- ### Get Charset Function Example Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md Example demonstrating how to extract the charset from a Content-Type header using the getCharset function. ```javascript // Request header: Content-Type: application/json; charset=UTF-8 const charset = getCharset(req) // 'utf-8' ``` -------------------------------- ### Generic Top-Level Middleware Setup Source: https://github.com/expressjs/body-parser/blob/master/README.md Add JSON and URL-encoded parsers as top-level middleware to parse all incoming request bodies. This is the simplest setup. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded()) // parse application/json app.use(bodyParser.json()) app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('you posted:\n') res.end(String(JSON.stringify(req.body, null, 2))) }) ``` -------------------------------- ### Importing and Basic Setup for JSON Parsing Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-json-parser.md Demonstrates how to import the body-parser module and apply the basic JSON parsing middleware to an Express application. This setup parses all incoming JSON requests. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // Basic setup - parse all JSON app.use(bodyParser.json()) ``` -------------------------------- ### Example Debug Output Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/configuration.md Example output when debug logging is enabled, showing internal operations of the body-parser middleware. ```text body-parser:json parse json +0ms body-parser:read body +2ms body-parser:json parse json +1ms ``` -------------------------------- ### Raw Body Storage Example Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md Demonstrates using the verify callback to store the raw request body as a string on the request object. ```javascript verify: (req, res, buf, encoding) => { req.rawBody = buf.toString(encoding) } ``` -------------------------------- ### Payload Size Validation Example Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md An example of using the verify callback to check if the request payload size exceeds a maximum limit. ```javascript verify: (req, res, buf, encoding) => { if (buf.length > MAX_SIZE) { throw new Error('Payload too large') } } ``` -------------------------------- ### Complete Request Processing Example with JSON Body Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md This snippet demonstrates setting up the body-parser middleware to handle JSON requests, including custom verification and logging. ```javascript const bodyParser = require('body-parser') const express = require('express') const app = express() // Using JSON parser as example app.use(bodyParser.json({ limit: '10mb', verify: (req, res, buf, encoding) => { console.log('Received', buf.length, 'bytes') } })) app.post('/', (req, res) => { res.json(req.body) }) ``` -------------------------------- ### Example Debug Output Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/utils-reference.md This is an example of the output you might see when debug logging is enabled for body-parser, showing events related to reading and parsing request bodies. ```text body-parser:read content-type "application/json" +0ms body-parser:read skip empty body +1ms body-parser:json parse json +0ms body-parser:read read body +2ms body-parser:read parse body +1ms ``` -------------------------------- ### Implementing the Verify Callback Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/types.md Example of implementing the verify callback to store raw body content on the request or to abort parsing for large payloads. ```javascript const bodyParser = require('body-parser') const parser = bodyParser.json({ verify: (req, res, buf, encoding) => { // Can store properties on req req.rawBody = buf.toString(encoding) // Can throw to abort if (buf.length > 1000000) { throw new Error('Payload too large') } } }) ``` -------------------------------- ### Signature Verification Example Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md A common use case for the verify callback: verifying a request signature using HMAC-SHA256. ```javascript verify: (req, res, buf, encoding) => { const signature = crypto .createHmac('sha256', SECRET) .update(buf) .digest('hex') if (signature !== req.headers['x-signature']) { throw new Error('Invalid signature') } } ``` -------------------------------- ### HTML Form Example Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-urlencoded-parser.md An example of an HTML form that submits data using the `application/x-www-form-urlencoded` content type, which is processed by the `body-parser.urlencoded()` middleware. ```html
Sends: application/x-www-form-urlencoded body with username=john&password=secret ``` -------------------------------- ### Bytes Library Parsing Examples Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/utils-reference.md Demonstrates how the 'bytes' library is used to parse human-readable size strings into byte counts. It also shows how invalid inputs are handled. ```javascript const bytes = require('bytes') bytes.parse('100kb') // 102400 bytes.parse('1mb') // 1048576 bytes.parse('10mb') // 10485760 bytes.parse('512b') // 512 bytes.parse(102400) // 102400 (numbers pass through) bytes.parse('invalid') // null (returns null on parse error) ``` ```javascript normalizeOptions({ limit: 'invalid' }, 'application/json') // TypeError: option limit "invalid" is invalid ``` -------------------------------- ### Global Middleware Setup with Body-Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-module.md Sets up body-parser middleware globally in an Express application to parse JSON and URL-encoded bodies for all routes. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // Parse JSON bodies app.use(bodyParser.json()) // Parse URL-encoded form bodies app.use(bodyParser.urlencoded({ extended: false })) // Now all routes have req.body populated app.post('/api/users', (req, res) => { console.log(req.body) // Parsed object }) app.listen(3000) ``` -------------------------------- ### Basic Express App Setup with Body-Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/index.md Sets up a basic Express application and applies JSON and URL-encoded body parsing middleware globally. This allows `req.body` to be populated with parsed request data in all subsequent route handlers. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // Global middleware app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.post('/api', (req, res) => { console.log(req.body) // Parsed object }) ``` -------------------------------- ### Handle Unsupported Content Encoding Errors Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md This example shows how to handle 'encoding.unsupported' errors, triggered by unsupported Content-Encoding headers or when inflate is disabled. It responds with a 415 status and information about the encoding. ```javascript app.use((err, req, res, next) => { if (err.type === 'encoding.unsupported') { return res.status(415).json({ error: 'Content encoding not supported', encoding: err.encoding }) } next(err) }) ``` -------------------------------- ### Verify Raw Content Before Decoding Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-text-parser.md Implement a 'verify' callback to perform checks on the raw request body buffer before it's decoded. This example calculates a SHA256 hash and checks the buffer length. ```javascript // Verify raw content before decoding const verifiedTextParser = bodyParser.text({ verify: (req, res, buf, encoding) => { // Store hash of raw bytes const crypto = require('crypto') req.contentHash = crypto .createHash('sha256') .update(buf) .digest('hex') // Validate size before decoding if (buf.length > 100000) { throw new Error('Content too large') } } }) app.post('/verified', verifiedTextParser, (req, res) => { res.json({ text: req.body, hash: req.contentHash }) }) ``` -------------------------------- ### Type Normalization Examples Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/utils-reference.md Illustrates how the 'type' option is normalized into a function for checking request content types. It supports string, array of strings, and function types. ```javascript // String type normalizeOptions({ type: 'json' }, 'application/json') // shouldParse = function that checks type-is(req, 'json') ``` ```javascript // Array of types normalizeOptions({ type: ['json', 'application/*+json'] }, 'application/json') // shouldParse = function that checks type-is(req, ['json', 'application/*+json']) ``` ```javascript // Function type (used as-is) const customChecker = (req) => req.headers['x-parse'] === 'true' normalizeOptions({ type: customChecker }, 'application/json') // shouldParse = customChecker (unchanged) ``` -------------------------------- ### URL-Encoded Parser Charset Validator Example Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md An example validator function for the URL-encoded parser, accepting only 'utf-8' or 'iso-8859-1' charsets. ```javascript isValidCharset: (charset) => charset === 'utf-8' || charset === 'iso-8859-1' // Only accepts these two charsets ``` -------------------------------- ### Handle Entity Verification Failed Errors Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md This example demonstrates handling 'entity.verify.failed' errors, which are thrown when a custom `verify` option callback fails. It responds with a 403 status and the error message from the callback. ```javascript app.use((err, req, res, next) => { if (err.type === 'entity.verify.failed') { return res.status(403).json({ error: 'Request verification failed', details: err.message }) } next(err) }) ``` -------------------------------- ### Verify Function Validation Examples Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/utils-reference.md Shows the validation for the 'verify' option, which must be a function or omitted. Non-function types result in a TypeError. ```javascript // Valid normalizeOptions({ verify: (req, res, buf, enc) => {} }, 'json') // verify stored in result ``` ```javascript // Invalid normalizeOptions({ verify: 'notafunction' }, 'json') // TypeError: option verify must be function ``` ```javascript normalizeOptions({ verify: true }, 'json') // TypeError: option verify must be function ``` -------------------------------- ### Example Route Handling Parsed JSON Body Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-json-parser.md Illustrates a basic Express.js POST route that utilizes the `bodyParser.json()` middleware to parse the incoming JSON request body and log it to the console. ```javascript app.post('/api/users', (req, res) => { console.log(req.body) // { name: 'John', age: 30 } res.json({ created: true }) }) ``` -------------------------------- ### Use Specific Parsers Instead of Deprecated bodyParser() Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md This example shows the error thrown when using the deprecated `bodyParser()` function without arguments. It advises using specific parsers like `bodyParser.json()` and `bodyParser.urlencoded()` instead. ```javascript const bodyParser = require('body-parser') app.use(bodyParser()) // Error thrown ``` ```javascript app.use(bodyParser.json()) app.use(bodyParser.urlencoded()) ``` -------------------------------- ### Verifying Binary Payload with Custom Logic Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-raw-parser.md Uses the 'verify' option in bodyParser.raw() to validate the binary payload. This example checks for PNG magic bytes and throws an error for invalid files, storing the raw buffer for potential auditing. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // Verify and validate binary payload const verifiedRawParser = bodyParser.raw({ verify: (req, res, buf, encoding) => { // Store raw buffer for later logging/auditing req.rawBuffer = buf // Validate magic bytes for specific file type if (buf.length >= 4) { const magic = buf.toString('hex', 0, 4) if (magic !== '89504e47') { // PNG magic number throw new Error('Invalid PNG file') } } } }) app.post('/upload/png', verifiedRawParser, (req, res) => { // Buffer already validated by verify callback res.json({ valid: true }) }) ``` -------------------------------- ### Parse All Text MIME Types with Wildcard Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-text-parser.md Use a wildcard 'text/*' type to parse any incoming request with a Content-Type starting with 'text/'. ```javascript // Wildcard matching for all text types app.post('/api/text-any', bodyParser.text({ type: 'text/*' }), (req, res) => { res.json({ received: req.body }) }) ``` -------------------------------- ### JSON Parser with Request Signature Verification Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-module.md Implement request signature verification using `bodyParser.json`'s `verify` option. This example computes an HMAC-SHA256 signature and compares it against the `x-signature` header. An error handler is included to catch verification failures. ```javascript const express = require('express') const bodyParser = require('body-parser') const crypto = require('crypto') const app = express() const SECRET = 'your-webhook-secret' const verifiedJsonParser = bodyParser.json({ verify: (req, res, buf, encoding) => { // Compute HMAC const signature = crypto .createHmac('sha256', SECRET) .update(buf) .digest('hex') req.signature = signature // Verify signature matches header const clientSignature = req.headers['x-signature'] if (!clientSignature || clientSignature !== signature) { throw new Error('Invalid signature') } } }) app.post('/webhook', verifiedJsonParser, (req, res) => { res.json({ verified: true }) }) // Error handler app.use((err, req, res, next) => { if (err.type === 'entity.verify.failed') { return res.status(403).json({ error: 'Invalid signature' }) } next(err) }) app.listen(3000) ``` -------------------------------- ### Importing and Initializing raw Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-raw-parser.md Demonstrates how to import the raw parser from the body-parser library and initialize it with optional configurations. ```javascript const raw = require('body-parser').raw const rawParser = raw([options]) ``` -------------------------------- ### Import and Initialize Text Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-text-parser.md Import the text parser and initialize it with default options to parse text/plain requests. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // Parse text/plain as string app.use(bodyParser.text()) ``` -------------------------------- ### JSON Parser Charset Validator Example Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md An example validator function for the JSON parser, accepting only UTF-8, UTF-16, and UTF-32 charsets. ```javascript isValidCharset: (charset) => charset.slice(0, 4) === 'utf-' // Only accepts 'utf-8', 'utf-16', 'utf-32', etc. ``` -------------------------------- ### Importing and Initializing urlencoded Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-urlencoded-parser.md Demonstrates how to import the `urlencoded` function from the `body-parser` module and initialize the parser middleware with optional configurations. ```javascript const urlencoded = require('body-parser').urlencoded const urlencodedParser = urlencoded([options]) ``` -------------------------------- ### Import Body-Parser Parsers Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/index.md Demonstrates how to import the body-parser module and its individual parser functions. This is the first step before using any of the parsing middleware. ```javascript const bodyParser = require('body-parser') // Or individual imports const json = require('body-parser/json') const urlencoded = require('body-parser/urlencoded') const raw = require('body-parser/raw') const text = require('body-parser/text') ``` -------------------------------- ### Get Charset from Content-Type Header Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/utils-reference.md Extracts and normalizes the charset from the Content-Type header. Returns the charset in lowercase or undefined if the header is missing, unparseable, or lacks a charset parameter. ```javascript const { getCharset } = require('./utils') // Request with header: Content-Type: application/json; charset=UTF-8 const charset = getCharset(req) // 'utf-8' ``` -------------------------------- ### Handle 'querystring.parse.rangeError' Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md This example demonstrates handling the 'querystring.parse.rangeError', which is triggered when the nesting depth of URL-encoded form data exceeds the configured limit. It responds with a 400 Bad Request status. ```javascript app.use((err, req, res, next) => { if (err.type === 'querystring.parse.rangeError') { return res.status(400).json({ error: 'Form structure too complex' }) } next(err) }) ``` -------------------------------- ### Direct Import of Body-Parser Parsers Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-module.md Import individual body-parser parsers directly from their respective files for potential tree-shaking benefits. This shows importing the JSON parser both via the main entry point and directly. ```javascript // Via main entry point const bodyParser = require('body-parser') const jsonParser = bodyParser.json() // Direct imports (equivalent) const json = require('body-parser/json') const jsonParser = json() // Other direct imports const raw = require('body-parser/raw') const text = require('body-parser/text') const urlencoded = require('body-parser/urlencoded') ``` -------------------------------- ### Set Default Charset for JSON Parsing Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/configuration.md Configure the default character encoding to use when the Content-Type header does not specify a charset. Only charsets starting with 'utf-' are supported; others will result in an error. ```javascript bodyParser.json({ defaultCharset: 'utf-8' }) ``` -------------------------------- ### Initialize JSON Parser with Invalid Limit Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md Demonstrates TypeErrors that occur when initializing the JSON parser with an invalid 'limit' option. The 'limit' option must be a valid byte string or number. ```javascript bodyParser.json({ limit: 'invalid' }) // TypeError bodyParser.json({ limit: {} }) // TypeError ``` -------------------------------- ### Custom JSON Reviver Function Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/types.md The `reviver` option allows you to transform parsed JSON values. This example converts ISO 8601 date strings into JavaScript Date objects during parsing. It follows the standard JSON.parse reviver signature. ```javascript const bodyParser = require('body-parser') const parser = bodyParser.json({ reviver: (key, value) => { // Convert ISO 8601 strings to Date objects if (typeof value === 'string' && /^ return new Date(value) } return value } }) ``` -------------------------------- ### bodyParser.raw([options]) Source: https://github.com/expressjs/body-parser/blob/master/README.md Parses all bodies as a Buffer. It only looks at requests where the Content-Type header matches the type option and supports automatic inflation of gzip, br, and deflate encodings. The parsed body is available as `req.body`. ```APIDOC ## bodyParser.raw([options]) ### Description Parses all bodies as a `Buffer` and only looks at requests where the `Content-Type` header matches the `type` option. This parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` encodings. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a `Buffer` object of the body. ### Options - **inflate** (boolean) - Optional - When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. - **limit** (string|number) - Optional - Controls the maximum request body size. Defaults to `'100kb'`. - **type** (string|string[]|function) - Optional - Used to determine what media type the middleware will parse. Defaults to `application/octet-stream`. - **verify** (function) - Optional - If supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ``` -------------------------------- ### Global Error Handling for JSON Parsing Errors Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-json-parser.md Provides an example of a global error handling middleware in Express.js to catch and respond to specific errors thrown by the JSON parser, such as parsing failures or requests exceeding the size limit. ```javascript app.use((err, req, res, next) => { if (err.type === 'entity.parse.failed') { return res.status(400).json({ error: 'Invalid JSON' }) } if (err.type === 'entity.too.large') { return res.status(413).json({ error: 'Request too large' }) } next(err) }) ``` -------------------------------- ### JSON Parsing with Custom Verification Callback Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-json-parser.md Illustrates using the 'verify' option to add a custom verification step before JSON parsing. This callback can be used for logging or to implement custom validation logic, such as checking body size. ```javascript const verifiedParser = bodyParser.json({ verify: (req, res, buf, encoding) => { // req.rawBody for logging/debugging req.rawBody = buf.toString(encoding) // Abort parsing by throwing if (buf.length > 1000000) { throw new Error('Body too large for verification') } } }) ``` -------------------------------- ### Custom Content-Type Matching for Binary Formats Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-raw-parser.md Configures the raw parser to accept specific custom binary MIME types in addition to the default 'application/octet-stream'. This allows for more granular control over which binary formats are parsed. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // Custom type matching for specific binary formats app.post('/api/binary', bodyParser.raw({ type: ['application/octet-stream', 'application/vnd.custom-binary'] }), (req, res) => { const buffer = req.body res.json({ bytes: buffer.length }) }) ``` -------------------------------- ### Iconv-lite Encoding Existence Check Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/utils-reference.md Demonstrates how to check if a character encoding is supported by the 'iconv-lite' library, which is used for text parsing. ```javascript const iconv = require('iconv-lite') iconv.encodingExists('utf-8') // true iconv.encodingExists('iso-8859-1') // true iconv.encodingExists('bogus') // false ``` -------------------------------- ### bodyParser.text([options]) Source: https://github.com/expressjs/body-parser/blob/master/README.md Parses all bodies as a string. It only looks at requests where the Content-Type header matches the type option and supports automatic inflation of gzip, br, and deflate encodings. The parsed body is available as `req.body`. ```APIDOC ## bodyParser.text([options]) ### Description Parses all bodies as a string and only looks at requests where the `Content-Type` header matches the `type` option. This parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` encodings. A new `body` string containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a string of the body. ### Options - **defaultCharset** (string) - Optional - Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. Defaults to `utf-8`. - **inflate** (boolean) - Optional - When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. - **limit** (string|number) - Optional - Controls the maximum request body size. Defaults to `'100kb'`. - **type** (string|string[]|function) - Optional - Used to determine what media type the middleware will parse. Defaults to `application/json`. ``` -------------------------------- ### Initialize JSON Parser with Invalid Verify Option Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md Shows TypeErrors resulting from providing an invalid 'verify' option to the JSON parser. The 'verify' option must be a function. ```javascript bodyParser.json({ verify: 'notafunction' }) // TypeError bodyParser.json({ verify: true }) // TypeError ``` -------------------------------- ### JSON Parsing with Custom Content-Type Matching Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-json-parser.md Demonstrates how to use the 'type' option with a function to define custom logic for matching the Content-Type header. This allows parsing JSON only when a specific custom header is present. ```javascript const customTypeParser = bodyParser.json({ type: (req) => { // Only parse if custom header present return req.headers['x-custom-json'] === 'true' } }) ``` -------------------------------- ### File Upload Handler with Raw Body Parsing Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/index.md Process binary file uploads by configuring body-parser to handle raw request bodies with a specified size limit. ```javascript app.post('/upload', bodyParser.raw({ limit: '50mb' }), (req, res) => { const buffer = req.body // Buffer const size = buffer.length // Process binary data res.json({ uploaded: size }) }) ``` -------------------------------- ### Handle Multiple Content Types with Different Parsers Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/index.md Apply multiple body-parser middleware instances to a route to handle different content types, such as JSON and plain text. ```javascript const json = bodyParser.json() const text = bodyParser.text() app.post('/multi', json, text, (req, res) => { // Parses both JSON and text res.json({ body: req.body }) }) ``` -------------------------------- ### Handling File Uploads with Raw Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-raw-parser.md Configures the raw parser to accept larger file uploads (up to 50MB) and processes the uploaded buffer to calculate its size and SHA256 hash. ```javascript const express = require('express') const bodyParser = require('body-parser') const crypto = require('crypto') const app = express() // Handle file uploads or binary data app.post('/api/upload', bodyParser.raw({ limit: '50mb' }), (req, res) => { const buffer = req.body // Buffer instance const size = buffer.length const hash = crypto.createHash('sha256').update(buffer).digest('hex') res.json({ uploaded: size, hash: hash }) }) ``` -------------------------------- ### Raw Parser Middleware Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/utils-reference.md Creates and returns the raw data parsing middleware. It normalizes options and sets skipCharset to true, as raw data does not rely on charset validation. ```javascript // lib/types/raw.js function raw (options) { const normalizedOptions = normalizeOptions(options, 'application/octet-stream') // Raw parser uses passthrough (no parsing transformation) const readOptions = { ...normalizedOptions, skipCharset: true // Skip charset validation for binary data } return function rawParser (req, res, next) { read(req, res, next, passthrough, debug, readOptions) } } ``` -------------------------------- ### Body-Parser Package Exports Configuration Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-module.md View the `exports` field in `package.json` which defines the entry points for direct imports of body-parser's individual parsers. ```json { "exports": { ".": "./index.js", "./json": "./lib/types/json.js", "./raw": "./lib/types/raw.js", "./text": "./lib/types/text.js", "./urlencoded": "./lib/types/urlencoded.js" } } ``` -------------------------------- ### Conditional Parser Selection with Body-Parser Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-module.md Demonstrates how to conditionally select and apply different body-parser middleware based on the request's Content-Type header for a webhook endpoint. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() const jsonParser = bodyParser.json() const textParser = bodyParser.text() const rawParser = bodyParser.raw() // Route that accepts multiple content types app.post('/webhook', (req, res, next) => { const contentType = req.headers['content-type'] if (contentType && contentType.includes('application/json')) { return jsonParser(req, res, next) } else if (contentType && contentType.includes('text/plain')) { return textParser(req, res, next) } else if (contentType && contentType.includes('octet-stream')) { return rawParser(req, res, next) } next() }) app.post('/webhook', (req, res) => { res.json({ received: true, type: typeof req.body }) }) app.listen(3000) ``` -------------------------------- ### Initialize URL-Encoded Parser with Invalid Depth Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md Demonstrates TypeErrors when initializing the URL-Encoded parser with an invalid 'depth' option (when extended is true). The 'depth' must be zero or a positive number. ```javascript bodyParser.urlencoded({ extended: true, depth: -1 }) // TypeError bodyParser.urlencoded({ extended: true, depth: NaN }) // TypeError ``` -------------------------------- ### Verify Callback Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/types.md The `verify` option allows for a custom callback function to be executed before parsing the request body. This callback can be used to inspect or modify the raw buffer, or to abort parsing by throwing an error. ```APIDOC ## Verify Callback The `verify` option accepts a callback with this signature: ```javascript verify(req: IncomingMessage, res: ServerResponse, buf: Buffer, encoding: string): void ``` | Parameter | Type | Description | |-----------|------|-------------| | req | http.IncomingMessage | Express request object | | res | http.ServerResponse | Express response object | | buf | Buffer | Raw request body as Buffer | | encoding | string \| null | Detected charset (null for binary parsers like raw) | **Return:** Must return `undefined`. Throw an error to abort parsing. ```javascript const bodyParser = require('body-parser') const parser = bodyParser.json({ verify: (req, res, buf, encoding) => { // Can store properties on req req.rawBody = buf.toString(encoding) // Can throw to abort if (buf.length > 1000000) { throw new Error('Payload too large') } } }) ``` ``` -------------------------------- ### Error Handling in Verification Callback Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/read-module-reference.md Illustrates the error handling logic within the verification callback. If the callback throws an error, it's caught and passed to the next middleware. ```javascript if (verify) { try { debug('verify body') verify(req, res, body, encoding) } catch (err) { next(createError(403, err, { body: body, type: err.type || 'entity.verify.failed' })) return } } ``` -------------------------------- ### Initialize URL-Encoded Parser with Invalid Parameter Limit Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/errors.md This snippet shows TypeErrors that occur when the URL-Encoded parser is initialized with an invalid 'parameterLimit'. The 'parameterLimit' must be a positive number. ```javascript bodyParser.urlencoded({ parameterLimit: -1 }) // TypeError bodyParser.urlencoded({ parameterLimit: 'abc' }) // TypeError bodyParser.urlencoded({ parameterLimit: NaN }) // TypeError ``` -------------------------------- ### Configure URL-Encoded Parser Depth Limit Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/configuration.md Sets the maximum object nesting depth in extended mode using the 'qs' library. Exceeding this depth throws an error. Must be zero or positive; NaN values throw a TypeError. ```javascript bodyParser.urlencoded({ extended: true, depth: 5 // Only allow 5 levels of nesting }) ``` -------------------------------- ### bodyParser.text([options]) Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-module.md Creates an Express middleware function that parses incoming request bodies as plain text strings. ```APIDOC ## bodyParser.text([options]) ### Description Parses incoming request bodies as plain text strings. ### Method Function factory that returns Express middleware. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (This function creates middleware that processes the request body). ### Request Example ```javascript app.use(bodyParser.text()) ``` ### Response Returns an Express middleware function. #### Success Response (200) N/A (Middleware processes the request body and populates `req.body` as a string). #### Response Example N/A ``` -------------------------------- ### Raw Parser Specific Options Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/types.md The raw parser has no specific options beyond the common ones. It always returns a Buffer. ```javascript { inflate?: boolean // Default: true limit?: string | number // Default: '100kb' type?: string | string[] | Function // Default: 'application/octet-stream' verify?: Function // Optional callback } ``` -------------------------------- ### Implement Custom Body Verification Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/configuration.md Provide a callback function to execute before parsing the request body. This is useful for tasks like storing the raw body, computing signatures, or validating payload integrity. Throwing an error within this callback will abort parsing. ```javascript bodyParser.json({ verify: (req, res, buf, encoding) => { // Store raw body req.rawBody = buf.toString(encoding) // Compute signature const crypto = require('crypto') req.signature = crypto .createHmac('sha256', 'secret') .update(buf) .digest('hex') // Abort with error if validation fails if (req.headers['x-signature'] !== req.signature) { throw new Error('Invalid signature') } } }) ``` -------------------------------- ### Configure URL-Encoded Parser Parameter Limit Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/configuration.md Sets the maximum number of form fields allowed. Requests exceeding this limit return an error. Must be a positive number; non-positive values or NaN throw a TypeError. ```javascript bodyParser.urlencoded({ parameterLimit: 100 }) ``` -------------------------------- ### Content-Type Matching via Function Source: https://github.com/expressjs/body-parser/blob/master/_autodocs/api-reference-raw-parser.md Uses a function to dynamically determine if a request should be parsed as raw binary data based on custom request headers. This provides flexibility for content-type matching beyond predefined strings. ```javascript const express = require('express') const bodyParser = require('body-parser') const app = express() // Match custom types via function app.post('/process', bodyParser.raw({ type: (req) => { // Only parse requests with x-binary header return req.headers['x-binary'] === 'true' } }), (req, res) => { const buffer = req.body res.json({ processed: buffer.length }) }) ```