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