You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

475 lines
19 KiB

6 months ago
  1. # body-parser
  2. [![NPM Version][npm-version-image]][npm-url]
  3. [![NPM Downloads][npm-downloads-image]][npm-url]
  4. [![Build Status][ci-image]][ci-url]
  5. [![Test Coverage][coveralls-image]][coveralls-url]
  6. [![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
  7. Node.js body parsing middleware.
  8. Parse incoming request bodies in a middleware before your handlers, available
  9. under the `req.body` property.
  10. **Note** As `req.body`'s shape is based on user-controlled input, all
  11. properties and values in this object are untrusted and should be validated
  12. before trusting. For example, `req.body.foo.toString()` may fail in multiple
  13. ways, for example the `foo` property may not be there or may not be a string,
  14. and `toString` may not be a function and instead a string or other user input.
  15. [Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
  16. _This does not handle multipart bodies_, due to their complex and typically
  17. large nature. For multipart bodies, you may be interested in the following
  18. modules:
  19. * [busboy](https://www.npmjs.org/package/busboy#readme) and
  20. [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
  21. * [multiparty](https://www.npmjs.org/package/multiparty#readme) and
  22. [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)
  23. * [formidable](https://www.npmjs.org/package/formidable#readme)
  24. * [multer](https://www.npmjs.org/package/multer#readme)
  25. This module provides the following parsers:
  26. * [JSON body parser](#bodyparserjsonoptions)
  27. * [Raw body parser](#bodyparserrawoptions)
  28. * [Text body parser](#bodyparsertextoptions)
  29. * [URL-encoded form body parser](#bodyparserurlencodedoptions)
  30. Other body parsers you might be interested in:
  31. - [body](https://www.npmjs.org/package/body#readme)
  32. - [co-body](https://www.npmjs.org/package/co-body#readme)
  33. ## Installation
  34. ```sh
  35. $ npm install body-parser
  36. ```
  37. ## API
  38. ```js
  39. var bodyParser = require('body-parser')
  40. ```
  41. The `bodyParser` object exposes various factories to create middlewares. All
  42. middlewares will populate the `req.body` property with the parsed body when
  43. the `Content-Type` request header matches the `type` option, or an empty
  44. object (`{}`) if there was no body to parse, the `Content-Type` was not matched,
  45. or an error occurred.
  46. The various errors returned by this module are described in the
  47. [errors section](#errors).
  48. ### bodyParser.json([options])
  49. Returns middleware that only parses `json` and only looks at requests where
  50. the `Content-Type` header matches the `type` option. This parser accepts any
  51. Unicode encoding of the body and supports automatic inflation of `gzip` and
  52. `deflate` encodings.
  53. A new `body` object containing the parsed data is populated on the `request`
  54. object after the middleware (i.e. `req.body`).
  55. #### Options
  56. The `json` function takes an optional `options` object that may contain any of
  57. the following keys:
  58. ##### inflate
  59. When set to `true`, then deflated (compressed) bodies will be inflated; when
  60. `false`, deflated bodies are rejected. Defaults to `true`.
  61. ##### limit
  62. Controls the maximum request body size. If this is a number, then the value
  63. specifies the number of bytes; if it is a string, the value is passed to the
  64. [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
  65. to `'100kb'`.
  66. ##### reviver
  67. The `reviver` option is passed directly to `JSON.parse` as the second
  68. argument. You can find more information on this argument
  69. [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).
  70. ##### strict
  71. When set to `true`, will only accept arrays and objects; when `false` will
  72. accept anything `JSON.parse` accepts. Defaults to `true`.
  73. ##### type
  74. The `type` option is used to determine what media type the middleware will
  75. parse. This option can be a string, array of strings, or a function. If not a
  76. function, `type` option is passed directly to the
  77. [type-is](https://www.npmjs.org/package/type-is#readme) library and this can
  78. be an extension name (like `json`), a mime type (like `application/json`), or
  79. a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`
  80. option is called as `fn(req)` and the request is parsed if it returns a truthy
  81. value. Defaults to `application/json`.
  82. ##### verify
  83. The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
  84. where `buf` is a `Buffer` of the raw request body and `encoding` is the
  85. encoding of the request. The parsing can be aborted by throwing an error.
  86. ### bodyParser.raw([options])
  87. Returns middleware that parses all bodies as a `Buffer` and only looks at
  88. requests where the `Content-Type` header matches the `type` option. This
  89. parser supports automatic inflation of `gzip` and `deflate` encodings.
  90. A new `body` object containing the parsed data is populated on the `request`
  91. object after the middleware (i.e. `req.body`). This will be a `Buffer` object
  92. of the body.
  93. #### Options
  94. The `raw` function takes an optional `options` object that may contain any of
  95. the following keys:
  96. ##### inflate
  97. When set to `true`, then deflated (compressed) bodies will be inflated; when
  98. `false`, deflated bodies are rejected. Defaults to `true`.
  99. ##### limit
  100. Controls the maximum request body size. If this is a number, then the value
  101. specifies the number of bytes; if it is a string, the value is passed to the
  102. [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
  103. to `'100kb'`.
  104. ##### type
  105. The `type` option is used to determine what media type the middleware will
  106. parse. This option can be a string, array of strings, or a function.
  107. If not a function, `type` option is passed directly to the
  108. [type-is](https://www.npmjs.org/package/type-is#readme) library and this
  109. can be an extension name (like `bin`), a mime type (like
  110. `application/octet-stream`), or a mime type with a wildcard (like `*/*` or
  111. `application/*`). If a function, the `type` option is called as `fn(req)`
  112. and the request is parsed if it returns a truthy value. Defaults to
  113. `application/octet-stream`.
  114. ##### verify
  115. The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
  116. where `buf` is a `Buffer` of the raw request body and `encoding` is the
  117. encoding of the request. The parsing can be aborted by throwing an error.
  118. ### bodyParser.text([options])
  119. Returns middleware that parses all bodies as a string and only looks at
  120. requests where the `Content-Type` header matches the `type` option. This
  121. parser supports automatic inflation of `gzip` and `deflate` encodings.
  122. A new `body` string containing the parsed data is populated on the `request`
  123. object after the middleware (i.e. `req.body`). This will be a string of the
  124. body.
  125. #### Options
  126. The `text` function takes an optional `options` object that may contain any of
  127. the following keys:
  128. ##### defaultCharset
  129. Specify the default character set for the text content if the charset is not
  130. specified in the `Content-Type` header of the request. Defaults to `utf-8`.
  131. ##### inflate
  132. When set to `true`, then deflated (compressed) bodies will be inflated; when
  133. `false`, deflated bodies are rejected. Defaults to `true`.
  134. ##### limit
  135. Controls the maximum request body size. If this is a number, then the value
  136. specifies the number of bytes; if it is a string, the value is passed to the
  137. [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
  138. to `'100kb'`.
  139. ##### type
  140. The `type` option is used to determine what media type the middleware will
  141. parse. This option can be a string, array of strings, or a function. If not
  142. a function, `type` option is passed directly to the
  143. [type-is](https://www.npmjs.org/package/type-is#readme) library and this can
  144. be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
  145. type with a wildcard (like `*/*` or `text/*`). If a function, the `type`
  146. option is called as `fn(req)` and the request is parsed if it returns a
  147. truthy value. Defaults to `text/plain`.
  148. ##### verify
  149. The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
  150. where `buf` is a `Buffer` of the raw request body and `encoding` is the
  151. encoding of the request. The parsing can be aborted by throwing an error.
  152. ### bodyParser.urlencoded([options])
  153. Returns middleware that only parses `urlencoded` bodies and only looks at
  154. requests where the `Content-Type` header matches the `type` option. This
  155. parser accepts only UTF-8 encoding of the body and supports automatic
  156. inflation of `gzip` and `deflate` encodings.
  157. A new `body` object containing the parsed data is populated on the `request`
  158. object after the middleware (i.e. `req.body`). This object will contain
  159. key-value pairs, where the value can be a string or array (when `extended` is
  160. `false`), or any type (when `extended` is `true`).
  161. #### Options
  162. The `urlencoded` function takes an optional `options` object that may contain
  163. any of the following keys:
  164. ##### extended
  165. The `extended` option allows to choose between parsing the URL-encoded data
  166. with the `querystring` library (when `false`) or the `qs` library (when
  167. `true`). The "extended" syntax allows for rich objects and arrays to be
  168. encoded into the URL-encoded format, allowing for a JSON-like experience
  169. with URL-encoded. For more information, please
  170. [see the qs library](https://www.npmjs.org/package/qs#readme).
  171. Defaults to `true`, but using the default has been deprecated. Please
  172. research into the difference between `qs` and `querystring` and choose the
  173. appropriate setting.
  174. ##### inflate
  175. When set to `true`, then deflated (compressed) bodies will be inflated; when
  176. `false`, deflated bodies are rejected. Defaults to `true`.
  177. ##### limit
  178. Controls the maximum request body size. If this is a number, then the value
  179. specifies the number of bytes; if it is a string, the value is passed to the
  180. [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
  181. to `'100kb'`.
  182. ##### parameterLimit
  183. The `parameterLimit` option controls the maximum number of parameters that
  184. are allowed in the URL-encoded data. If a request contains more parameters
  185. than this value, a 413 will be returned to the client. Defaults to `1000`.
  186. ##### type
  187. The `type` option is used to determine what media type the middleware will
  188. parse. This option can be a string, array of strings, or a function. If not
  189. a function, `type` option is passed directly to the
  190. [type-is](https://www.npmjs.org/package/type-is#readme) library and this can
  191. be an extension name (like `urlencoded`), a mime type (like
  192. `application/x-www-form-urlencoded`), or a mime type with a wildcard (like
  193. `*/x-www-form-urlencoded`). If a function, the `type` option is called as
  194. `fn(req)` and the request is parsed if it returns a truthy value. Defaults
  195. to `application/x-www-form-urlencoded`.
  196. ##### verify
  197. The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
  198. where `buf` is a `Buffer` of the raw request body and `encoding` is the
  199. encoding of the request. The parsing can be aborted by throwing an error.
  200. #### depth
  201. 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.
  202. ## Errors
  203. The middlewares provided by this module create errors using the
  204. [`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
  205. will typically have a `status`/`statusCode` property that contains the suggested
  206. HTTP response code, an `expose` property to determine if the `message` property
  207. should be displayed to the client, a `type` property to determine the type of
  208. error without matching against the `message`, and a `body` property containing
  209. the read body, if available.
  210. The following are the common errors created, though any error can come through
  211. for various reasons.
  212. ### content encoding unsupported
  213. This error will occur when the request had a `Content-Encoding` header that
  214. contained an encoding but the "inflation" option was set to `false`. The
  215. `status` property is set to `415`, the `type` property is set to
  216. `'encoding.unsupported'`, and the `charset` property will be set to the
  217. encoding that is unsupported.
  218. ### entity parse failed
  219. This error will occur when the request contained an entity that could not be
  220. parsed by the middleware. The `status` property is set to `400`, the `type`
  221. property is set to `'entity.parse.failed'`, and the `body` property is set to
  222. the entity value that failed parsing.
  223. ### entity verify failed
  224. This error will occur when the request contained an entity that could not be
  225. failed verification by the defined `verify` option. The `status` property is
  226. set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
  227. `body` property is set to the entity value that failed verification.
  228. ### request aborted
  229. This error will occur when the request is aborted by the client before reading
  230. the body has finished. The `received` property will be set to the number of
  231. bytes received before the request was aborted and the `expected` property is
  232. set to the number of expected bytes. The `status` property is set to `400`
  233. and `type` property is set to `'request.aborted'`.
  234. ### request entity too large
  235. This error will occur when the request body's size is larger than the "limit"
  236. option. The `limit` property will be set to the byte limit and the `length`
  237. property will be set to the request body's length. The `status` property is
  238. set to `413` and the `type` property is set to `'entity.too.large'`.
  239. ### request size did not match content length
  240. This error will occur when the request's length did not match the length from
  241. the `Content-Length` header. This typically occurs when the request is malformed,
  242. typically when the `Content-Length` header was calculated based on characters
  243. instead of bytes. The `status` property is set to `400` and the `type` property
  244. is set to `'request.size.invalid'`.
  245. ### stream encoding should not be set
  246. This error will occur when something called the `req.setEncoding` method prior
  247. to this middleware. This module operates directly on bytes only and you cannot
  248. call `req.setEncoding` when using this module. The `status` property is set to
  249. `500` and the `type` property is set to `'stream.encoding.set'`.
  250. ### stream is not readable
  251. This error will occur when the request is no longer readable when this middleware
  252. attempts to read it. This typically means something other than a middleware from
  253. this module read the request body already and the middleware was also configured to
  254. read the same request. The `status` property is set to `500` and the `type`
  255. property is set to `'stream.not.readable'`.
  256. ### too many parameters
  257. This error will occur when the content of the request exceeds the configured
  258. `parameterLimit` for the `urlencoded` parser. The `status` property is set to
  259. `413` and the `type` property is set to `'parameters.too.many'`.
  260. ### unsupported charset "BOGUS"
  261. This error will occur when the request had a charset parameter in the
  262. `Content-Type` header, but the `iconv-lite` module does not support it OR the
  263. parser does not support it. The charset is contained in the message as well
  264. as in the `charset` property. The `status` property is set to `415`, the
  265. `type` property is set to `'charset.unsupported'`, and the `charset` property
  266. is set to the charset that is unsupported.
  267. ### unsupported content encoding "bogus"
  268. This error will occur when the request had a `Content-Encoding` header that
  269. contained an unsupported encoding. The encoding is contained in the message
  270. as well as in the `encoding` property. The `status` property is set to `415`,
  271. the `type` property is set to `'encoding.unsupported'`, and the `encoding`
  272. property is set to the encoding that is unsupported.
  273. ### The input exceeded the depth
  274. 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.
  275. ## Examples
  276. ### Express/Connect top-level generic
  277. This example demonstrates adding a generic JSON and URL-encoded parser as a
  278. top-level middleware, which will parse the bodies of all incoming requests.
  279. This is the simplest setup.
  280. ```js
  281. var express = require('express')
  282. var bodyParser = require('body-parser')
  283. var app = express()
  284. // parse application/x-www-form-urlencoded
  285. app.use(bodyParser.urlencoded({ extended: false }))
  286. // parse application/json
  287. app.use(bodyParser.json())
  288. app.use(function (req, res) {
  289. res.setHeader('Content-Type', 'text/plain')
  290. res.write('you posted:\n')
  291. res.end(JSON.stringify(req.body, null, 2))
  292. })
  293. ```
  294. ### Express route-specific
  295. This example demonstrates adding body parsers specifically to the routes that
  296. need them. In general, this is the most recommended way to use body-parser with
  297. Express.
  298. ```js
  299. var express = require('express')
  300. var bodyParser = require('body-parser')
  301. var app = express()
  302. // create application/json parser
  303. var jsonParser = bodyParser.json()
  304. // create application/x-www-form-urlencoded parser
  305. var urlencodedParser = bodyParser.urlencoded({ extended: false })
  306. // POST /login gets urlencoded bodies
  307. app.post('/login', urlencodedParser, function (req, res) {
  308. res.send('welcome, ' + req.body.username)
  309. })
  310. // POST /api/users gets JSON bodies
  311. app.post('/api/users', jsonParser, function (req, res) {
  312. // create user in req.body
  313. })
  314. ```
  315. ### Change accepted type for parsers
  316. All the parsers accept a `type` option which allows you to change the
  317. `Content-Type` that the middleware will parse.
  318. ```js
  319. var express = require('express')
  320. var bodyParser = require('body-parser')
  321. var app = express()
  322. // parse various different custom JSON types as JSON
  323. app.use(bodyParser.json({ type: 'application/*+json' }))
  324. // parse some custom thing into a Buffer
  325. app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
  326. // parse an HTML body into a string
  327. app.use(bodyParser.text({ type: 'text/html' }))
  328. ```
  329. ## License
  330. [MIT](LICENSE)
  331. [ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci
  332. [ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
  333. [coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master
  334. [coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
  335. [node-version-image]: https://badgen.net/npm/node/body-parser
  336. [node-version-url]: https://nodejs.org/en/download
  337. [npm-downloads-image]: https://badgen.net/npm/dm/body-parser
  338. [npm-url]: https://npmjs.org/package/body-parser
  339. [npm-version-image]: https://badgen.net/npm/v/body-parser
  340. [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge
  341. [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser