body-parser

repository·master·Indexed 26 days ago

https://github.com/expressjs/body-parser

Node.js body parsing middleware (version 2.3.0) used to parse incoming request bodies and make the data available on the req.body object. It supports JSON, raw, text, and URL-encoded formats via specific middleware factories: bodyParser.json(), bodyParser.raw(), bodyParser.text(), and bodyParser.urlencoded(). It does not handle multipart bodies.

Tokens
3.1K
Snippets
5
Records
20
Agent score
88%

What's inside body-parser

  1. Overview of body-parser middleware

    master

    body-parser is a Node.js middleware that parses incoming request bodies and makes them available under the req.body property.

    Security Warning: Because req.body is based on user-controlled input, all properties and values are untrusted. You must validate all data before use. For example, calling req.body.foo.toString() is unsafe because foo might be missing, might not be a string, or toString might not be a function.

    Limitations: This module does not handle multipart bodies (e.g., file uploads). For multipart bodies, use modules such as busboy, multiparty, formidable, or multer.

  2. Change the accepted Content-Type for parsers

    master

    All parsers accept a type option. Use this to instruct the middleware to parse custom or non-standard Content-Type headers.

    const express = require('express')
    const bodyParser = require('body-parser')
    
    const app = express()
    
    // parse various different custom JSON types as JSON
    app.use(bodyParser.json({ type: 'application/*+json' }))
    
    // parse some custom thing into a Buffer
    app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
    
    // parse an HTML body into a string
    app.use(bodyParser.text({ type: 'text/html' }))
  3. Use body-parser as top-level middleware

    master

    To parse the bodies of all incoming requests in an Express application, add bodyParser.urlencoded() and bodyParser.json() as top-level middleware using app.use(). This is the simplest setup but applies to every request.

    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)))
    })
  4. Use body-parser for specific Express routes

    master

    The recommended way to use body-parser is to apply specific parsers only to the routes that require them. This prevents unnecessary parsing on routes that do not expect a body.

    const express = require('express')
    const bodyParser = require('body-parser')
    
    const app = express()
    
    // create application/json parser
    const jsonParser = bodyParser.json()
    
    // create application/x-www-form-urlencoded parser
    const urlencodedParser = bodyParser.urlencoded()
    
    // POST /login gets urlencoded bodies
    app.post('/login', urlencodedParser, function (req, res) {
      if (!req.body || !req.body.username) res.sendStatus(400)
      res.send('welcome, ' + req.body.username)
    })
    
    // POST /api/users gets JSON bodies
    app.post('/api/users', jsonParser, function (req, res) {
      if (!req.body) res.sendStatus(400)
      // create user in req.body
    })
  5. Import body-parser and its individual parsers

    master

    You can import the main body-parser object to access all middleware factories, or import specific parsers directly to reduce your dependency footprint.

    // Import all parsers
    const bodyParser = require('body-parser')
    
    // Or import individual parsers directly
    const json = require('body-parser/json')
    const urlencoded = require('body-parser/urlencoded')
    const raw = require('body-parser/raw')
    const text = require('body-parser/text')
    // Import all parsers
    const bodyParser = require('body-parser')
    
    // Or import individual parsers directly
    const json = require('body-parser/json')
    const urlencoded = require('body-parser/urlencoded')
    const raw = require('body-parser/raw')
    const text = require('body-parser/text')
  6. Use bodyParser.json() to parse JSON bodies

    master

    Returns middleware that parses json bodies and populates req.body with the parsed data. It supports automatic inflation of gzip, br (brotli), and deflate encodings.

    Common Options:

    • defaultCharset: Default character set if not specified in Content-Type. Defaults to utf-8.
    • inflate: Whether to inflate compressed bodies. Defaults to true.
    • limit: Maximum request body size (e.g., '100kb'). Defaults to '100kb'. High limits (e.g., > 5MB) are discouraged due to memory and performance risks.
    • reviver: A function passed to JSON.parse as the second argument.
    • strict: If true, only accepts arrays and objects. Defaults to true.
    • type: Media type to parse (string, array, or function). Defaults to application/json.
    • verify: A function verify(req, res, buf, encoding) called with the raw buffer. Throwing an error here aborts parsing.
  7. Use bodyParser.text() to parse text bodies

    master

    Returns middleware that parses all bodies as a string and populates req.body. Supports automatic inflation of gzip, br (brotli), and deflate encodings.

    Common Options:

    • defaultCharset: Default character set if not specified in Content-Type. Defaults to utf-8.
    • inflate: Whether to inflate compressed bodies. Defaults to true.
    • limit: Maximum request body size. Defaults to '100kb'.
    • type: Media type to parse (string, array, or function). Defaults to text/plain.
    • verify: A function verify(req, res, buf, encoding) called with the raw buffer. Throwing an error here aborts parsing.
  8. Use bodyParser.raw() to parse raw Buffer bodies

    master

    Returns middleware that parses all bodies as a Buffer and populates req.body. Supports automatic inflation of gzip, br (brotli), and deflate encodings.

    Common Options:

    • inflate: Whether to inflate compressed bodies. Defaults to true.
    • limit: Maximum request body size. Defaults to '100kb'.
    • type: Media type to parse (string, array, or function). Defaults to application/octet-stream.
    • verify: A function verify(req, res, buf, encoding) called with the raw buffer. Throwing an error here aborts parsing.
  9. Use bodyParser.urlencoded() to parse URL-encoded bodies

    master

    Returns middleware that parses urlencoded bodies and populates req.body with key-value pairs. Supports gzip, br, and deflate inflation.

    Common Options:

    • extended: If true, uses the qs library to allow rich objects and arrays to be encoded. Defaults to false.
    • inflate: Whether to inflate compressed bodies. Defaults to true.
    • limit: Maximum request body size. Defaults to '100kb'.
    • parameterLimit: Maximum number of parameters allowed. Defaults to 1000.
    • type: Media type to parse. Defaults to application/x-www-form-urlencoded.
    • verify: A function verify(req, res, buf, encoding) called with the raw buffer. Throwing an error here aborts parsing.
    • defaultCharset: Default charset (utf-8 or iso-8859-1). Defaults to utf-8.
    • charsetSentinel: Whether to let the utf8 parameter take precedence. Defaults to false.
    • interpretNumericEntities: Whether to decode numeric entities (e.g., ☺) when parsing iso-8859-1. Defaults to false.
    • depth: Maximum depth for qs when extended is true. Defaults to 32.
  10. Configure urlencoded() options

    master

    When calling urlencoded(options), you can provide the following configuration options:

    • extended: A boolean. If true, uses the qs library for parsing (allowing for nested objects and arrays). If false, uses a simpler parsing logic. Defaults to false (implied by Boolean(options?.extended)).
    • parameterLimit: A positive number specifying the maximum number of parameters allowed in the body. Defaults to 1000. Throws a TypeError if the value is not a positive number.
    • depth: A zero or positive number specifying the depth of nested objects. Only applicable if extended is true. Defaults to 32 if extended is true, otherwise 0.
    • defaultCharset: The default character set to use. Must be either 'utf-8' or 'iso-8859-1'. Throws a TypeError if an invalid charset is provided.
    • charsetSentinel: Passed directly to the underlying qs parser.
    • interpretNumericEntities: Passed directly to the underlying qs parser.
  11. Handle body-parser errors

    master
    The middlewares use the http-errors module. Errors typically include a status/statusCode property, an expose property (to determine if the message should be shown to the client), a type property for error categorization, and a body property containing the read body if available.