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.

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