Projekt

Obecné

Profil

Stáhnout (16.7 KB) Statistiky
| Větev: | Revize:
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

    
8
Node.js body parsing middleware.
9

    
10
Parse incoming request bodies in a middleware before your handlers, available
11
under the `req.body` property.
12

    
13
**Note** As `req.body`'s shape is based on user-controlled input, all
14
properties and values in this object are untrusted and should be validated
15
before trusting. For example, `req.body.foo.toString()` may fail in multiple
16
ways, for example the `foo` property may not be there or may not be a string,
17
and `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
22
large nature. For multipart bodies, you may be interested in the following
23
modules:
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

    
32
This 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

    
39
Other 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
55
var bodyParser = require('body-parser')
56
```
57

    
58
The `bodyParser` object exposes various factories to create middlewares. All
59
middlewares will populate the `req.body` property with the parsed body when
60
the `Content-Type` request header matches the `type` option, or an empty
61
object (`{}`) if there was no body to parse, the `Content-Type` was not matched,
62
or an error occurred.
63

    
64
The various errors returned by this module are described in the
65
[errors section](#errors).
66

    
67
### bodyParser.json([options])
68

    
69
Returns middleware that only parses `json` and only looks at requests where
70
the `Content-Type` header matches the `type` option. This parser accepts any
71
Unicode encoding of the body and supports automatic inflation of `gzip` and
72
`deflate` encodings.
73

    
74
A new `body` object containing the parsed data is populated on the `request`
75
object after the middleware (i.e. `req.body`).
76

    
77
#### Options
78

    
79
The `json` function takes an optional `options` object that may contain any of
80
the following keys:
81

    
82
##### inflate
83

    
84
When set to `true`, then deflated (compressed) bodies will be inflated; when
85
`false`, deflated bodies are rejected. Defaults to `true`.
86

    
87
##### limit
88

    
89
Controls the maximum request body size. If this is a number, then the value
90
specifies 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
92
to `'100kb'`.
93

    
94
##### reviver
95

    
96
The `reviver` option is passed directly to `JSON.parse` as the second
97
argument. 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

    
102
When set to `true`, will only accept arrays and objects; when `false` will
103
accept anything `JSON.parse` accepts. Defaults to `true`.
104

    
105
##### type
106

    
107
The `type` option is used to determine what media type the middleware will
108
parse. This option can be a string, array of strings, or a function. If not a
109
function, `type` option is passed directly to the
110
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
111
be an extension name (like `json`), a mime type (like `application/json`), or
112
a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`
113
option is called as `fn(req)` and the request is parsed if it returns a truthy
114
value. Defaults to `application/json`.
115

    
116
##### verify
117

    
118
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
119
where `buf` is a `Buffer` of the raw request body and `encoding` is the
120
encoding of the request. The parsing can be aborted by throwing an error.
121

    
122
### bodyParser.raw([options])
123

    
124
Returns middleware that parses all bodies as a `Buffer` and only looks at
125
requests where the `Content-Type` header matches the `type` option. This
126
parser supports automatic inflation of `gzip` and `deflate` encodings.
127

    
128
A new `body` object containing the parsed data is populated on the `request`
129
object after the middleware (i.e. `req.body`). This will be a `Buffer` object
130
of the body.
131

    
132
#### Options
133

    
134
The `raw` function takes an optional `options` object that may contain any of
135
the following keys:
136

    
137
##### inflate
138

    
139
When set to `true`, then deflated (compressed) bodies will be inflated; when
140
`false`, deflated bodies are rejected. Defaults to `true`.
141

    
142
##### limit
143

    
144
Controls the maximum request body size. If this is a number, then the value
145
specifies 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
147
to `'100kb'`.
148

    
149
##### type
150

    
151
The `type` option is used to determine what media type the middleware will
152
parse. This option can be a string, array of strings, or a function.
153
If not a function, `type` option is passed directly to the
154
[type-is](https://www.npmjs.org/package/type-is#readme) library and this
155
can 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)`
158
and the request is parsed if it returns a truthy value. Defaults to
159
`application/octet-stream`.
160

    
161
##### verify
162

    
163
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
164
where `buf` is a `Buffer` of the raw request body and `encoding` is the
165
encoding of the request. The parsing can be aborted by throwing an error.
166

    
167
### bodyParser.text([options])
168

    
169
Returns middleware that parses all bodies as a string and only looks at
170
requests where the `Content-Type` header matches the `type` option. This
171
parser supports automatic inflation of `gzip` and `deflate` encodings.
172

    
173
A new `body` string containing the parsed data is populated on the `request`
174
object after the middleware (i.e. `req.body`). This will be a string of the
175
body.
176

    
177
#### Options
178

    
179
The `text` function takes an optional `options` object that may contain any of
180
the following keys:
181

    
182
##### defaultCharset
183

    
184
Specify the default character set for the text content if the charset is not
185
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
186

    
187
##### inflate
188

    
189
When set to `true`, then deflated (compressed) bodies will be inflated; when
190
`false`, deflated bodies are rejected. Defaults to `true`.
191

    
192
##### limit
193

    
194
Controls the maximum request body size. If this is a number, then the value
195
specifies 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
197
to `'100kb'`.
198

    
199
##### type
200

    
201
The `type` option is used to determine what media type the middleware will
202
parse. This option can be a string, array of strings, or a function. If not
203
a function, `type` option is passed directly to the
204
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
205
be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
206
type with a wildcard (like `*/*` or `text/*`). If a function, the `type`
207
option is called as `fn(req)` and the request is parsed if it returns a
208
truthy value. Defaults to `text/plain`.
209

    
210
##### verify
211

    
212
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
213
where `buf` is a `Buffer` of the raw request body and `encoding` is the
214
encoding of the request. The parsing can be aborted by throwing an error.
215

    
216
### bodyParser.urlencoded([options])
217

    
218
Returns middleware that only parses `urlencoded` bodies and only looks at
219
requests where the `Content-Type` header matches the `type` option. This
220
parser accepts only UTF-8 encoding of the body and supports automatic
221
inflation of `gzip` and `deflate` encodings.
222

    
223
A new `body` object containing the parsed data is populated on the `request`
224
object after the middleware (i.e. `req.body`). This object will contain
225
key-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

    
230
The `urlencoded` function takes an optional `options` object that may contain
231
any of the following keys:
232

    
233
##### extended
234

    
235
The `extended` option allows to choose between parsing the URL-encoded data
236
with the `querystring` library (when `false`) or the `qs` library (when
237
`true`). The "extended" syntax allows for rich objects and arrays to be
238
encoded into the URL-encoded format, allowing for a JSON-like experience
239
with URL-encoded. For more information, please
240
[see the qs library](https://www.npmjs.org/package/qs#readme).
241

    
242
Defaults to `true`, but using the default has been deprecated. Please
243
research into the difference between `qs` and `querystring` and choose the
244
appropriate setting.
245

    
246
##### inflate
247

    
248
When set to `true`, then deflated (compressed) bodies will be inflated; when
249
`false`, deflated bodies are rejected. Defaults to `true`.
250

    
251
##### limit
252

    
253
Controls the maximum request body size. If this is a number, then the value
254
specifies 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
256
to `'100kb'`.
257

    
258
##### parameterLimit
259

    
260
The `parameterLimit` option controls the maximum number of parameters that
261
are allowed in the URL-encoded data. If a request contains more parameters
262
than this value, a 413 will be returned to the client. Defaults to `1000`.
263

    
264
##### type
265

    
266
The `type` option is used to determine what media type the middleware will
267
parse. This option can be a string, array of strings, or a function. If not
268
a function, `type` option is passed directly to the
269
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
270
be 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
274
to `application/x-www-form-urlencoded`.
275

    
276
##### verify
277

    
278
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
279
where `buf` is a `Buffer` of the raw request body and `encoding` is the
280
encoding of the request. The parsing can be aborted by throwing an error.
281

    
282
## Errors
283

    
284
The middlewares provided by this module create errors depending on the error
285
condition during parsing. The errors will typically have a `status`/`statusCode`
286
property that contains the suggested HTTP response code, an `expose` property
287
to 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

    
291
The following are the common errors emitted, though any error can come through
292
for various reasons.
293

    
294
### content encoding unsupported
295

    
296
This error will occur when the request had a `Content-Encoding` header that
297
contained 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
300
encoding that is unsupported.
301

    
302
### request aborted
303

    
304
This error will occur when the request is aborted by the client before reading
305
the body has finished. The `received` property will be set to the number of
306
bytes received before the request was aborted and the `expected` property is
307
set to the number of expected bytes. The `status` property is set to `400`
308
and `type` property is set to `'request.aborted'`.
309

    
310
### request entity too large
311

    
312
This error will occur when the request body's size is larger than the "limit"
313
option. The `limit` property will be set to the byte limit and the `length`
314
property will be set to the request body's length. The `status` property is
315
set to `413` and the `type` property is set to `'entity.too.large'`.
316

    
317
### request size did not match content length
318

    
319
This error will occur when the request's length did not match the length from
320
the `Content-Length` header. This typically occurs when the request is malformed,
321
typically when the `Content-Length` header was calculated based on characters
322
instead of bytes. The `status` property is set to `400` and the `type` property
323
is set to `'request.size.invalid'`.
324

    
325
### stream encoding should not be set
326

    
327
This error will occur when something called the `req.setEncoding` method prior
328
to this middleware. This module operates directly on bytes only and you cannot
329
call `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

    
334
This 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

    
340
This 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
342
parser does not support it. The charset is contained in the message as well
343
as in the `charset` property. The `status` property is set to `415`, the
344
`type` property is set to `'charset.unsupported'`, and the `charset` property
345
is set to the charset that is unsupported.
346

    
347
### unsupported content encoding "bogus"
348

    
349
This error will occur when the request had a `Content-Encoding` header that
350
contained an unsupported encoding. The encoding is contained in the message
351
as well as in the `encoding` property. The `status` property is set to `415`,
352
the `type` property is set to `'encoding.unsupported'`, and the `encoding`
353
property is set to the encoding that is unsupported.
354

    
355
## Examples
356

    
357
### Express/Connect top-level generic
358

    
359
This example demonstrates adding a generic JSON and URL-encoded parser as a
360
top-level middleware, which will parse the bodies of all incoming requests.
361
This is the simplest setup.
362

    
363
```js
364
var express = require('express')
365
var bodyParser = require('body-parser')
366

    
367
var app = express()
368

    
369
// parse application/x-www-form-urlencoded
370
app.use(bodyParser.urlencoded({ extended: false }))
371

    
372
// parse application/json
373
app.use(bodyParser.json())
374

    
375
app.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

    
384
This example demonstrates adding body parsers specifically to the routes that
385
need them. In general, this is the most recommended way to use body-parser with
386
Express.
387

    
388
```js
389
var express = require('express')
390
var bodyParser = require('body-parser')
391

    
392
var app = express()
393

    
394
// create application/json parser
395
var jsonParser = bodyParser.json()
396

    
397
// create application/x-www-form-urlencoded parser
398
var urlencodedParser = bodyParser.urlencoded({ extended: false })
399

    
400
// POST /login gets urlencoded bodies
401
app.post('/login', urlencodedParser, function (req, res) {
402
  res.send('welcome, ' + req.body.username)
403
})
404

    
405
// POST /api/users gets JSON bodies
406
app.post('/api/users', jsonParser, function (req, res) {
407
  // create user in req.body
408
})
409
```
410

    
411
### Change accepted type for parsers
412

    
413
All the parsers accept a `type` option which allows you to change the
414
`Content-Type` that the middleware will parse.
415

    
416
```js
417
var express = require('express')
418
var bodyParser = require('body-parser')
419

    
420
var app = express()
421

    
422
// parse various different custom JSON types as JSON
423
app.use(bodyParser.json({ type: 'application/*+json' }))
424

    
425
// parse some custom thing into a Buffer
426
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
427

    
428
// parse an HTML body into a string
429
app.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
(3-3/5)