Node.js body parsing middleware
npm install @sailshq/body-parser[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
[![Gratipay][gratipay-image]][gratipay-url]
Node.js body parsing middleware.
_This does not handle multipart bodies_, due to their complex and typically
large nature. For multipart bodies, you may be interested in the following
modules:
* busboy and
connect-busboy
* multiparty and
connect-multiparty
* formidable
* multer
This module provides the following parsers:
* JSON body parser
* Raw body parser
* Text body parser
* URL-encoded form body parser
Other body parsers you might be interested in:
``sh`
$ npm install body-parser
`js`
var bodyParser = require('body-parser')
The bodyParser object exposes various factories to create middlewares. Allreq.body
middlewares will populate the property with the parsed body or
provide an error to the callback. The various errors are described in the
errors section.
Returns middleware that only parses json. This parser accepts any Unicodegzip
encoding of the body and supports automatic inflation of and deflate
encodings.
A new body object containing the parsed data is populated on the requestreq.body
object after the middleware (i.e. ).
#### Options
The json function takes an option options object that may contain any of
the following keys:
##### inflate
When set to true, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults to true.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
bytes library for parsing. Defaults
to '100kb'.
##### reviver
The reviver option is passed directly to JSON.parse as the second
argument. You can find more information on this argument
in the MDN documentation about JSON.parse.
##### strict
When set to true, will only accept arrays and objects; when false willJSON.parse
accept anything accepts. Defaults to true.
##### type
The type option is used to determine what media type the middleware willtype
parse. This option can be a function or a string. If a string, optionjson
is passed directly to the type-is
library and this can be an extension name (like ), a mime type (likeapplication/json), or a mime type with a wildcard (like / or */json).type
If a function, the option is called as fn(req) and the request isapplication/json
parsed if it returns a truthy value. Defaults to .
##### verify
The verify option, if supplied, is called as verify(req, res, buf, encoding),buf
where is a Buffer of the raw request body and encoding is the
encoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that parses all bodies as a Buffer. This parsergzip
supports automatic inflation of and deflate encodings.
A new body object containing the parsed data is populated on the requestreq.body
object after the middleware (i.e. ). This will be a Buffer object
of the body.
#### Options
The raw function takes an option options object that may contain any of
the following keys:
##### inflate
When set to true, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults to true.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
bytes library for parsing. Defaults
to '100kb'.
##### type
The type option is used to determine what media type the middleware willtype
parse. This option can be a function or a string. If a string, optionbin
is passed directly to the type-is
library and this can be an extension name (like ), a mime type (likeapplication/octet-stream), or a mime type with a wildcard (like / orapplication/*). If a function, the type option is called as fn(req)application/octet-stream
and the request is parsed if it returns a truthy value. Defaults to.
##### verify
The verify option, if supplied, is called as verify(req, res, buf, encoding),buf
where is a Buffer of the raw request body and encoding is the
encoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that parses all bodies as a string. This parser supports
automatic inflation of gzip and deflate encodings.
A new body string containing the parsed data is populated on the requestreq.body
object after the middleware (i.e. ). This will be a string of the
body.
#### Options
The text function takes an option options object that may contain any of
the following keys:
##### defaultCharset
Specify the default character set for the text content if the charset is not
specified in the Content-Type header of the request. Defaults to utf-8.
##### inflate
When set to true, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults to true.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
bytes library for parsing. Defaults
to '100kb'.
##### type
The type option is used to determine what media type the middleware willtype
parse. This option can be a function or a string. If a string, optiontxt
is passed directly to the type-is
library and this can be an extension name (like ), a mime type (liketext/plain), or a mime type with a wildcard (like / or text/*).type
If a function, the option is called as fn(req) and the request istext/plain
parsed if it returns a truthy value. Defaults to .
##### verify
The verify option, if supplied, is called as verify(req, res, buf, encoding),buf
where is a Buffer of the raw request body and encoding is the
encoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that only parses urlencoded bodies. This parser acceptsgzip
only UTF-8 encoding of the body and supports automatic inflation of deflate
and encodings.
A new body object containing the parsed data is populated on the requestreq.body
object after the middleware (i.e. ). This object will containextended
key-value pairs, where the value can be a string or array (when isfalse), or any type (when extended is true).
#### Options
The urlencoded function takes an option options object that may contain
any of the following keys:
##### extended
The extended option allows to choose between parsing the URL-encoded dataquerystring
with the library (when false) or the qs library (whentrue). The "extended" syntax allows for rich objects and arrays to be
encoded into the URL-encoded format, allowing for a JSON-like experience
with URL-encoded. For more information, please
see the qs library.
Defaults to true, but using the default has been deprecated. Pleaseqs
research into the difference between and querystring and choose the
appropriate setting.
##### inflate
When set to true, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults to true.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
bytes library for parsing. Defaults
to '100kb'.
##### parameterLimit
The parameterLimit option controls the maximum number of parameters that1000
are allowed in the URL-encoded data. If a request contains more parameters
than this value, a 413 will be returned to the client. Defaults to .
##### type
The type option is used to determine what media type the middleware willtype
parse. This option can be a function or a string. If a string, optionurlencoded
is passed directly to the type-is
library and this can be an extension name (like ), a mime type (likeapplication/x-www-form-urlencoded), or a mime type with a wildcard (like*/x-www-form-urlencoded). If a function, the type option is called asfn(req) and the request is parsed if it returns a truthy value. Defaultsapplication/x-www-form-urlencoded
to .
##### verify
The verify option, if supplied, is called as verify(req, res, buf, encoding),buf
where is a Buffer of the raw request body and encoding is the
encoding of the request. The parsing can be aborted by throwing an error.
The middlewares provided by this module create errors depending on the error
condition during parsing. The errors will typically have a status property
that contains the suggested HTTP response code.
The following are the common errors emitted, though any error can come through
for various reasons.
This error will occur when the request had a Content-Encoding header thatfalse
contained an encoding but the "inflation" option was set to . Thestatus property is set to 415.
This error will occur when the request is aborted by the client before reading
the body has finished. The received property will be set to the number ofexpected
bytes received before the request was aborted and the property isstatus
set to the number of expected bytes. The property is set to 400.
This error will occur when the request body's size is larger than the "limit"
option. The limit property will be set to the byte limit and the lengthstatus
property will be set to the request body's length. The property is413
set to .
This error will occur when the request's length did not match the length from
the Content-Length header. This typically occurs when the requst is malformed,Content-Length
typically when the header was calculated based on charactersstatus
instead of bytes. The property is set to 400.
This error will occur when something called the req.setEncoding method priorreq.setEncoding
to this middleware. This module operates directly on bytes only and you cannot
call when using this module. The status property is set to500.
This error will occur when the request had a charset parameter in the
Content-Type header, but the iconv-lite module does not support it OR thecharset
parser does not support it. The charset is contained in the message as well
as in the property. The status property is set to 415.
This error will occur when the request had a Content-Encoding header thatencoding
contained an unsupported encoding. The encoding is contained in the message
as well as in the property. The status property is set to 415.
This example demonstrates adding a generic JSON and URL-encoded parser as a
top-level middleware, which will parse the bodies of all incoming requests.
This is the simplest setup.
`js
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
`
This example demonstrates adding body parsers specifically to the routes that
need them. In general, this is the most recommend way to use body-parser with
express.
`js
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})
`
All the parsers accept a type option which allows you to change theContent-Type that the middleware will parse.
`js
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))
``
[npm-image]: https://img.shields.io/npm/v/body-parser.svg
[npm-url]: https://npmjs.org/package/body-parser
[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg
[travis-url]: https://travis-ci.org/expressjs/body-parser
[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg
[downloads-url]: https://npmjs.org/package/body-parser
[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg
[gratipay-url]: https://www.gratipay.com/dougwilson/