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]
8 Node.js body parsing middleware.
10 Parse incoming request bodies in a middleware before your handlers, available
11 under the `req.body` property.
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.
19 [Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
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
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)
32 This module provides the following parsers:
34 * [JSON body parser](#bodyparserjsonoptions)
35 * [Raw body parser](#bodyparserrawoptions)
36 * [Text body parser](#bodyparsertextoptions)
37 * [URL-encoded form body parser](#bodyparserurlencodedoptions)
39 Other body parsers you might be interested in:
41 - [body](https://www.npmjs.org/package/body#readme)
42 - [co-body](https://www.npmjs.org/package/co-body#readme)
47 $ npm install body-parser
52 <!-- eslint-disable no-unused-vars -->
55 var bodyParser = require('body-parser')
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,
64 The various errors returned by this module are described in the
65 [errors section](#errors).
67 ### bodyParser.json([options])
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
74 A new `body` object containing the parsed data is populated on the `request`
75 object after the middleware (i.e. `req.body`).
79 The `json` function takes an optional `options` object that may contain any of
84 When set to `true`, then deflated (compressed) bodies will be inflated; when
85 `false`, deflated bodies are rejected. Defaults to `true`.
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
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).
102 When set to `true`, will only accept arrays and objects; when `false` will
103 accept anything `JSON.parse` accepts. Defaults to `true`.
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`.
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.
122 ### bodyParser.raw([options])
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.
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
134 The `raw` function takes an optional `options` object that may contain any of
139 When set to `true`, then deflated (compressed) bodies will be inflated; when
140 `false`, deflated bodies are rejected. Defaults to `true`.
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
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`.
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.
167 ### bodyParser.text([options])
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.
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
179 The `text` function takes an optional `options` object that may contain any of
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`.
189 When set to `true`, then deflated (compressed) bodies will be inflated; when
190 `false`, deflated bodies are rejected. Defaults to `true`.
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
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`.
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.
216 ### bodyParser.urlencoded([options])
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.
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`).
230 The `urlencoded` function takes an optional `options` object that may contain
231 any of the following keys:
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).
242 Defaults to `true`, but using the default has been deprecated. Please
243 research into the difference between `qs` and `querystring` and choose the
248 When set to `true`, then deflated (compressed) bodies will be inflated; when
249 `false`, deflated bodies are rejected. Defaults to `true`.
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
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`.
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`.
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.
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.
291 The following are the common errors emitted, though any error can come through
294 ### content encoding unsupported
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.
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'`.
310 ### request entity too large
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'`.
317 ### request size did not match content length
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'`.
325 ### stream encoding should not be set
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'`.
332 ### too many parameters
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'`.
338 ### unsupported charset "BOGUS"
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.
347 ### unsupported content encoding "bogus"
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.
357 ### Express/Connect top-level generic
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.
364 var express = require('express')
365 var bodyParser = require('body-parser')
369 // parse application/x-www-form-urlencoded
370 app.use(bodyParser.urlencoded({ extended: false }))
372 // parse application/json
373 app.use(bodyParser.json())
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))
382 ### Express route-specific
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
389 var express = require('express')
390 var bodyParser = require('body-parser')
394 // create application/json parser
395 var jsonParser = bodyParser.json()
397 // create application/x-www-form-urlencoded parser
398 var urlencodedParser = bodyParser.urlencoded({ extended: false })
400 // POST /login gets urlencoded bodies
401 app.post('/login', urlencodedParser, function (req, res) {
402 if (!req.body) return res.sendStatus(400)
403 res.send('welcome, ' + req.body.username)
406 // POST /api/users gets JSON bodies
407 app.post('/api/users', jsonParser, function (req, res) {
408 if (!req.body) return res.sendStatus(400)
409 // create user in req.body
413 ### Change accepted type for parsers
415 All the parsers accept a `type` option which allows you to change the
416 `Content-Type` that the middleware will parse.
419 var express = require('express')
420 var bodyParser = require('body-parser')
424 // parse various different custom JSON types as JSON
425 app.use(bodyParser.json({ type: 'application/*+json' }))
427 // parse some custom thing into a Buffer
428 app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
430 // parse an HTML body into a string
431 app.use(bodyParser.text({ type: 'text/html' }))
438 [npm-image]: https://img.shields.io/npm/v/body-parser.svg
439 [npm-url]: https://npmjs.org/package/body-parser
440 [travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg
441 [travis-url]: https://travis-ci.org/expressjs/body-parser
442 [coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg
443 [coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
444 [downloads-image]: https://img.shields.io/npm/dm/body-parser.svg
445 [downloads-url]: https://npmjs.org/package/body-parser