UNPKG

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