UNPKG

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