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