Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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