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