|
|
# body-parser
[![NPM Version][npm-version-image]][npm-url][![NPM Downloads][npm-downloads-image]][npm-url][![Build Status][ci-image]][ci-url][![Test Coverage][coveralls-image]][coveralls-url][![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
Node.js body parsing middleware.
Parse incoming request bodies in a middleware before your handlers, availableunder the `req.body` property.
**Note** As `req.body`'s shape is based on user-controlled input, allproperties and values in this object are untrusted and should be validatedbefore trusting. For example, `req.body.foo.toString()` may fail in multipleways, for example the `foo` property may not be there or may not be a string,and `toString` may not be a function and instead a string or other user input.
[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
_This does not handle multipart bodies_, due to their complex and typicallylarge nature. For multipart bodies, you may be interested in the followingmodules:
* [busboy](https://www.npmjs.org/package/busboy#readme) and [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) * [multiparty](https://www.npmjs.org/package/multiparty#readme) and [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) * [formidable](https://www.npmjs.org/package/formidable#readme) * [multer](https://www.npmjs.org/package/multer#readme)
This module provides the following parsers:
* [JSON body parser](#bodyparserjsonoptions) * [Raw body parser](#bodyparserrawoptions) * [Text body parser](#bodyparsertextoptions) * [URL-encoded form body parser](#bodyparserurlencodedoptions)
Other body parsers you might be interested in:
- [body](https://www.npmjs.org/package/body#readme)- [co-body](https://www.npmjs.org/package/co-body#readme)
## Installation
```sh$ npm install body-parser```
## API
```jsvar bodyParser = require('body-parser')```
The `bodyParser` object exposes various factories to create middlewares. Allmiddlewares will populate the `req.body` property with the parsed body whenthe `Content-Type` request header matches the `type` option, or an emptyobject (`{}`) if there was no body to parse, the `Content-Type` was not matched,or an error occurred.
The various errors returned by this module are described in the[errors section](#errors).
### bodyParser.json([options])
Returns middleware that only parses `json` and only looks at requests wherethe `Content-Type` header matches the `type` option. This parser accepts anyUnicode encoding of the body and supports automatic inflation of `gzip` and`deflate` encodings.
A new `body` object containing the parsed data is populated on the `request`object after the middleware (i.e. `req.body`).
#### Options
The `json` function takes an optional `options` object that may contain any ofthe following keys:
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to the[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaultsto `'100kb'`.
##### reviver
The `reviver` option is passed directly to `JSON.parse` as the secondargument. You can find more information on this argument[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
##### strict
When set to `true`, will only accept arrays and objects; when `false` willaccept anything `JSON.parse` accepts. Defaults to `true`.
##### type
The `type` option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function. If not afunction, `type` option is passed directly to the[type-is](https://www.npmjs.org/package/type-is#readme) library and this canbe an extension name (like `json`), a mime type (like `application/json`), ora mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`option is called as `fn(req)` and the request is parsed if it returns a truthyvalue. Defaults to `application/json`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,where `buf` is a `Buffer` of the raw request body and `encoding` is theencoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.raw([options])
Returns middleware that parses all bodies as a `Buffer` and only looks atrequests where the `Content-Type` header matches the `type` option. Thisparser supports automatic inflation of `gzip` 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` objectof the body.
#### Options
The `raw` function takes an optional `options` object that may contain any ofthe following keys:
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to the[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaultsto `'100kb'`.
##### type
The `type` option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function.If not a function, `type` option is passed directly to the[type-is](https://www.npmjs.org/package/type-is#readme) library and thiscan be an extension name (like `bin`), a mime type (like`application/octet-stream`), or a mime type with a wildcard (like `*/*` or`application/*`). If a function, the `type` option is called as `fn(req)`and the request is parsed if it returns a truthy value. Defaults to`application/octet-stream`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,where `buf` is a `Buffer` of the raw request body and `encoding` is theencoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.text([options])
Returns middleware that parses all bodies as a string and only looks atrequests where the `Content-Type` header matches the `type` option. Thisparser supports automatic inflation of `gzip` 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 thebody.
#### Options
The `text` function takes an optional `options` object that may contain any ofthe following keys:
##### defaultCharset
Specify the default character set for the text content if the charset is notspecified in the `Content-Type` header of the request. Defaults to `utf-8`.
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to the[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaultsto `'100kb'`.
##### type
The `type` option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function. If nota function, `type` option is passed directly to the[type-is](https://www.npmjs.org/package/type-is#readme) library and this canbe an extension name (like `txt`), a mime type (like `text/plain`), or a mimetype with a wildcard (like `*/*` or `text/*`). If a function, the `type`option is called as `fn(req)` and the request is parsed if it returns atruthy value. Defaults to `text/plain`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,where `buf` is a `Buffer` of the raw request body and `encoding` is theencoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.urlencoded([options])
Returns middleware that only parses `urlencoded` bodies and only looks atrequests where the `Content-Type` header matches the `type` option. Thisparser accepts only UTF-8 encoding of the body and supports automaticinflation of `gzip` 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 object will containkey-value pairs, where the value can be a string or array (when `extended` is`false`), or any type (when `extended` is `true`).
#### Options
The `urlencoded` function takes an optional `options` object that may containany of the following keys:
##### extended
The `extended` option allows to choose between parsing the URL-encoded datawith the `querystring` library (when `false`) or the `qs` library (when`true`). The "extended" syntax allows for rich objects and arrays to beencoded into the URL-encoded format, allowing for a JSON-like experiencewith URL-encoded. For more information, please[see the qs library](https://www.npmjs.org/package/qs#readme).
Defaults to `true`, but using the default has been deprecated. Pleaseresearch into the difference between `qs` and `querystring` and choose theappropriate setting.
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to the[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaultsto `'100kb'`.
##### parameterLimit
The `parameterLimit` option controls the maximum number of parameters thatare allowed in the URL-encoded data. If a request contains more parametersthan this value, a 413 will be returned to the client. Defaults to `1000`.
##### type
The `type` option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function. If nota function, `type` option is passed directly to the[type-is](https://www.npmjs.org/package/type-is#readme) library and this canbe an extension name (like `urlencoded`), a mime type (like`application/x-www-form-urlencoded`), or a mime type with a wildcard (like`*/x-www-form-urlencoded`). If a function, the `type` option is called as`fn(req)` and the request is parsed if it returns a truthy value. Defaultsto `application/x-www-form-urlencoded`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,where `buf` is a `Buffer` of the raw request body and `encoding` is theencoding of the request. The parsing can be aborted by throwing an error.
#### depth
The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible.
## Errors
The middlewares provided by this module create errors using the[`http-errors` module](https://www.npmjs.com/package/http-errors). The errorswill typically have a `status`/`statusCode` property that contains the suggestedHTTP response code, an `expose` property to determine if the `message` propertyshould be displayed to the client, a `type` property to determine the type oferror without matching against the `message`, and a `body` property containingthe read body, if available.
The following are the common errors created, though any error can come throughfor various reasons.
### content encoding unsupported
This error will occur when the request had a `Content-Encoding` header thatcontained an encoding but the "inflation" option was set to `false`. The`status` property is set to `415`, the `type` property is set to`'encoding.unsupported'`, and the `charset` property will be set to theencoding that is unsupported.
### entity parse failed
This error will occur when the request contained an entity that could not beparsed by the middleware. The `status` property is set to `400`, the `type`property is set to `'entity.parse.failed'`, and the `body` property is set tothe entity value that failed parsing.
### entity verify failed
This error will occur when the request contained an entity that could not befailed verification by the defined `verify` option. The `status` property isset to `403`, the `type` property is set to `'entity.verify.failed'`, and the`body` property is set to the entity value that failed verification.
### request aborted
This error will occur when the request is aborted by the client before readingthe body has finished. The `received` property will be set to the number ofbytes received before the request was aborted and the `expected` property isset to the number of expected bytes. The `status` property is set to `400`and `type` property is set to `'request.aborted'`.
### request entity too large
This error will occur when the request body's size is larger than the "limit"option. The `limit` property will be set to the byte limit and the `length`property will be set to the request body's length. The `status` property isset to `413` and the `type` property is set to `'entity.too.large'`.
### request size did not match content length
This error will occur when the request's length did not match the length fromthe `Content-Length` header. This typically occurs when the request is malformed,typically when the `Content-Length` header was calculated based on charactersinstead of bytes. The `status` property is set to `400` and the `type` propertyis set to `'request.size.invalid'`.
### stream encoding should not be set
This error will occur when something called the `req.setEncoding` method priorto this middleware. This module operates directly on bytes only and you cannotcall `req.setEncoding` when using this module. The `status` property is set to`500` and the `type` property is set to `'stream.encoding.set'`.
### stream is not readable
This error will occur when the request is no longer readable when this middlewareattempts to read it. This typically means something other than a middleware fromthis module read the request body already and the middleware was also configured toread the same request. The `status` property is set to `500` and the `type`property is set to `'stream.not.readable'`.
### too many parameters
This error will occur when the content of the request exceeds the configured`parameterLimit` for the `urlencoded` parser. The `status` property is set to`413` and the `type` property is set to `'parameters.too.many'`.
### unsupported charset "BOGUS"
This error will occur when the request had a charset parameter in the`Content-Type` header, but the `iconv-lite` module does not support it OR theparser does not support it. The charset is contained in the message as wellas in the `charset` property. The `status` property is set to `415`, the`type` property is set to `'charset.unsupported'`, and the `charset` propertyis set to the charset that is unsupported.
### unsupported content encoding "bogus"
This error will occur when the request had a `Content-Encoding` header thatcontained an unsupported encoding. The encoding is contained in the messageas well as in the `encoding` property. The `status` property is set to `415`,the `type` property is set to `'encoding.unsupported'`, and the `encoding`property is set to the encoding that is unsupported.
### The input exceeded the depth
This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown.
## Examples
### Express/Connect top-level generic
This example demonstrates adding a generic JSON and URL-encoded parser as atop-level middleware, which will parse the bodies of all incoming requests.This is the simplest setup.
```jsvar express = require('express')var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: false }))
// parse application/jsonapp.use(bodyParser.json())
app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('you posted:\n') res.end(JSON.stringify(req.body, null, 2))})```
### Express route-specific
This example demonstrates adding body parsers specifically to the routes thatneed them. In general, this is the most recommended way to use body-parser withExpress.
```jsvar express = require('express')var bodyParser = require('body-parser')
var app = express()
// create application/json parservar jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parservar urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodiesapp.post('/login', urlencodedParser, function (req, res) { res.send('welcome, ' + req.body.username)})
// POST /api/users gets JSON bodiesapp.post('/api/users', jsonParser, function (req, res) { // create user in req.body})```
### Change accepted type for parsers
All the parsers accept a `type` option which allows you to change the`Content-Type` that the middleware will parse.
```jsvar express = require('express')var bodyParser = require('body-parser')
var app = express()
// parse various different custom JSON types as JSONapp.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Bufferapp.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a stringapp.use(bodyParser.text({ type: 'text/html' }))```
## License
[MIT](LICENSE)
[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master[node-version-image]: https://badgen.net/npm/node/body-parser[node-version-url]: https://nodejs.org/en/download[npm-downloads-image]: https://badgen.net/npm/dm/body-parser[npm-url]: https://npmjs.org/package/body-parser[npm-version-image]: https://badgen.net/npm/v/body-parser[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser
|