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.

445 lines
17 KiB

  1. # body-parser
  2. [![NPM Version][npm-image]][npm-url]
  3. [![NPM Downloads][downloads-image]][downloads-url]
  4. [![Build Status][travis-image]][travis-url]
  5. [![Test Coverage][coveralls-image]][coveralls-url]
  6. Node.js body parsing middleware.
  7. Parse incoming request bodies in a middleware before your handlers, available
  8. under the `req.body` property.
  9. **Note** As `req.body`'s shape is based on user-controlled input, all
  10. properties and values in this object are untrusted and should be validated
  11. before trusting. For example, `req.body.foo.toString()` may fail in multiple
  12. ways, for example the `foo` property may not be there or may not be a string,
  13. and `toString` may not be a function and instead a string or other user input.
  14. [Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
  15. _This does not handle multipart bodies_, due to their complex and typically
  16. large nature. For multipart bodies, you may be interested in the following
  17. modules:
  18. * [busboy](https://www.npmjs.org/package/busboy#readme) and
  19. [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
  20. * [multiparty](https://www.npmjs.org/package/multiparty#readme) and
  21. [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)
  22. * [formidable](https://www.npmjs.org/package/formidable#readme)
  23. * [multer](https://www.npmjs.org/package/multer#readme)
  24. This module provides the following parsers:
  25. * [JSON body parser](#bodyparserjsonoptions)
  26. * [Raw body parser](#bodyparserrawoptions)
  27. * [Text body parser](#bodyparsertextoptions)
  28. * [URL-encoded form body parser](#bodyparserurlencodedoptions)
  29. Other body parsers you might be interested in:
  30. - [body](https://www.npmjs.org/package/body#readme)
  31. - [co-body](https://www.npmjs.org/package/co-body#readme)
  32. ## Installation
  33. ```sh
  34. $ npm install body-parser
  35. ```
  36. ## API
  37. <!-- eslint-disable no-unused-vars -->
  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. ## Errors
  201. The middlewares provided by this module create errors depending on the error
  202. condition during parsing. The errors will typically have a `status`/`statusCode`
  203. property that contains the suggested HTTP response code, an `expose` property
  204. to determine if the `message` property should be displayed to the client, a
  205. `type` property to determine the type of error without matching against the
  206. `message`, and a `body` property containing the read body, if available.
  207. The following are the common errors emitted, though any error can come through
  208. for various reasons.
  209. ### content encoding unsupported
  210. This error will occur when the request had a `Content-Encoding` header that
  211. contained an encoding but the "inflation" option was set to `false`. The
  212. `status` property is set to `415`, the `type` property is set to
  213. `'encoding.unsupported'`, and the `charset` property will be set to the
  214. encoding that is unsupported.
  215. ### request aborted
  216. This error will occur when the request is aborted by the client before reading
  217. the body has finished. The `received` property will be set to the number of
  218. bytes received before the request was aborted and the `expected` property is
  219. set to the number of expected bytes. The `status` property is set to `400`
  220. and `type` property is set to `'request.aborted'`.
  221. ### request entity too large
  222. This error will occur when the request body's size is larger than the "limit"
  223. option. The `limit` property will be set to the byte limit and the `length`
  224. property will be set to the request body's length. The `status` property is
  225. set to `413` and the `type` property is set to `'entity.too.large'`.
  226. ### request size did not match content length
  227. This error will occur when the request's length did not match the length from
  228. the `Content-Length` header. This typically occurs when the request is malformed,
  229. typically when the `Content-Length` header was calculated based on characters
  230. instead of bytes. The `status` property is set to `400` and the `type` property
  231. is set to `'request.size.invalid'`.
  232. ### stream encoding should not be set
  233. This error will occur when something called the `req.setEncoding` method prior
  234. to this middleware. This module operates directly on bytes only and you cannot
  235. call `req.setEncoding` when using this module. The `status` property is set to
  236. `500` and the `type` property is set to `'stream.encoding.set'`.
  237. ### too many parameters
  238. This error will occur when the content of the request exceeds the configured
  239. `parameterLimit` for the `urlencoded` parser. The `status` property is set to
  240. `413` and the `type` property is set to `'parameters.too.many'`.
  241. ### unsupported charset "BOGUS"
  242. This error will occur when the request had a charset parameter in the
  243. `Content-Type` header, but the `iconv-lite` module does not support it OR the
  244. parser does not support it. The charset is contained in the message as well
  245. as in the `charset` property. The `status` property is set to `415`, the
  246. `type` property is set to `'charset.unsupported'`, and the `charset` property
  247. is set to the charset that is unsupported.
  248. ### unsupported content encoding "bogus"
  249. This error will occur when the request had a `Content-Encoding` header that
  250. contained an unsupported encoding. The encoding is contained in the message
  251. as well as in the `encoding` property. The `status` property is set to `415`,
  252. the `type` property is set to `'encoding.unsupported'`, and the `encoding`
  253. property is set to the encoding that is unsupported.
  254. ## Examples
  255. ### Express/Connect top-level generic
  256. This example demonstrates adding a generic JSON and URL-encoded parser as a
  257. top-level middleware, which will parse the bodies of all incoming requests.
  258. This is the simplest setup.
  259. ```js
  260. var express = require('express')
  261. var bodyParser = require('body-parser')
  262. var app = express()
  263. // parse application/x-www-form-urlencoded
  264. app.use(bodyParser.urlencoded({ extended: false }))
  265. // parse application/json
  266. app.use(bodyParser.json())
  267. app.use(function (req, res) {
  268. res.setHeader('Content-Type', 'text/plain')
  269. res.write('you posted:\n')
  270. res.end(JSON.stringify(req.body, null, 2))
  271. })
  272. ```
  273. ### Express route-specific
  274. This example demonstrates adding body parsers specifically to the routes that
  275. need them. In general, this is the most recommended way to use body-parser with
  276. Express.
  277. ```js
  278. var express = require('express')
  279. var bodyParser = require('body-parser')
  280. var app = express()
  281. // create application/json parser
  282. var jsonParser = bodyParser.json()
  283. // create application/x-www-form-urlencoded parser
  284. var urlencodedParser = bodyParser.urlencoded({ extended: false })
  285. // POST /login gets urlencoded bodies
  286. app.post('/login', urlencodedParser, function (req, res) {
  287. if (!req.body) return res.sendStatus(400)
  288. res.send('welcome, ' + req.body.username)
  289. })
  290. // POST /api/users gets JSON bodies
  291. app.post('/api/users', jsonParser, function (req, res) {
  292. if (!req.body) return res.sendStatus(400)
  293. // create user in req.body
  294. })
  295. ```
  296. ### Change accepted type for parsers
  297. All the parsers accept a `type` option which allows you to change the
  298. `Content-Type` that the middleware will parse.
  299. ```js
  300. var express = require('express')
  301. var bodyParser = require('body-parser')
  302. var app = express()
  303. // parse various different custom JSON types as JSON
  304. app.use(bodyParser.json({ type: 'application/*+json' }))
  305. // parse some custom thing into a Buffer
  306. app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
  307. // parse an HTML body into a string
  308. app.use(bodyParser.text({ type: 'text/html' }))
  309. ```
  310. ## License
  311. [MIT](LICENSE)
  312. [npm-image]: https://img.shields.io/npm/v/body-parser.svg
  313. [npm-url]: https://npmjs.org/package/body-parser
  314. [travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg
  315. [travis-url]: https://travis-ci.org/expressjs/body-parser
  316. [coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg
  317. [coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
  318. [downloads-image]: https://img.shields.io/npm/dm/body-parser.svg
  319. [downloads-url]: https://npmjs.org/package/body-parser