Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork753
Node.js body parsing middleware
License
expressjs/body-parser
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Node.js body parsing middleware.
Parse incoming request bodies in a middleware before your handlers, availableunder thereq.body property.
Note Asreq.body's shape is based on user-controlled input, allproperties and values in this object are untrusted and should be validatedbefore trusting. For example,req.body.foo.toString() may fail in multipleways, for example thefoo property may not be there or may not be a string,andtoString may not be a function and instead a string or other user input.
Learn about the anatomy of an HTTP transaction in Node.js.
This does not handle multipart bodies, due to their complex and typicallylarge nature. For multipart bodies, you may be interested in the followingmodules:
This module provides the following parsers:
Other body parsers you might be interested in:
$ npm install body-parser
varbodyParser=require('body-parser')
ThebodyParser object exposes various factories to create middlewares. Allmiddlewares will populate thereq.body property with the parsed body whentheContent-Type request header matches thetype option.
The various errors returned by this module are described in theerrors section.
Returns middleware that only parsesjson and only looks at requests wheretheContent-Type header matches thetype option. This parser accepts anyUnicode encoding of the body and supports automatic inflation ofgzip,br (brotli) anddeflate encodings.
A newbody object containing the parsed data is populated on therequestobject after the middleware (i.e.req.body).
Thejson function takes an optionaloptions object that may contain any ofthe following keys:
When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to thebytes library for parsing. Defaultsto'100kb'.
Thereviver option is passed directly toJSON.parse as the secondargument. You can find more information on this argumentin the MDN documentation about JSON.parse.
When set totrue, will only accept arrays and objects; whenfalse willaccept anythingJSON.parse accepts. Defaults totrue.
Thetype option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function. If not afunction,type option is passed directly to thetype-is library and this canbe an extension name (likejson), a mime type (likeapplication/json), ora mime type with a wildcard (like*/* or*/json). If a function, thetypeoption is called asfn(req) and the request is parsed if it returns a truthyvalue. Defaults toapplication/json.
Theverify option, if supplied, is called asverify(req, res, buf, encoding),wherebuf is aBuffer of the raw request body andencoding is theencoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that parses all bodies as aBuffer and only looks atrequests where theContent-Type header matches thetype option. Thisparser supports automatic inflation ofgzip,br (brotli) anddeflateencodings.
A newbody object containing the parsed data is populated on therequestobject after the middleware (i.e.req.body). This will be aBuffer objectof the body.
Theraw function takes an optionaloptions object that may contain any ofthe following keys:
When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to thebytes library for parsing. Defaultsto'100kb'.
Thetype option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function.If not a function,type option is passed directly to thetype-is library and thiscan be an extension name (likebin), a mime type (likeapplication/octet-stream), or a mime type with a wildcard (like*/* orapplication/*). If a function, thetype option is called asfn(req)and the request is parsed if it returns a truthy value. Defaults toapplication/octet-stream.
Theverify option, if supplied, is called asverify(req, res, buf, encoding),wherebuf is aBuffer of the raw request body andencoding is theencoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that parses all bodies as a string and only looks atrequests where theContent-Type header matches thetype option. Thisparser supports automatic inflation ofgzip,br (brotli) anddeflateencodings.
A newbody string containing the parsed data is populated on therequestobject after the middleware (i.e.req.body). This will be a string of thebody.
Thetext function takes an optionaloptions object that may contain any ofthe following keys:
Specify the default character set for the text content if the charset is notspecified in theContent-Type header of the request. Defaults toutf-8.
When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to thebytes library for parsing. Defaultsto'100kb'.
Thetype option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function. If nota function,type option is passed directly to thetype-is library and this canbe an extension name (liketxt), a mime type (liketext/plain), or a mimetype with a wildcard (like*/* ortext/*). If a function, thetypeoption is called asfn(req) and the request is parsed if it returns atruthy value. Defaults totext/plain.
Theverify option, if supplied, is called asverify(req, res, buf, encoding),wherebuf is aBuffer of the raw request body andencoding is theencoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that only parsesurlencoded bodies and only looks atrequests where theContent-Type header matches thetype option. Thisparser accepts only UTF-8 encoding of the body and supports automaticinflation ofgzip,br (brotli) anddeflate encodings.
A newbody object containing the parsed data is populated on therequestobject after the middleware (i.e.req.body). This object will containkey-value pairs, where the value can be a string or array (whenextended isfalse), or any type (whenextended istrue).
Theurlencoded function takes an optionaloptions object that may containany of the following keys:
The "extended" syntax allows for rich objects and arrays to be encoded into theURL-encoded format, allowing for a JSON-like experience with URL-encoded. Formore information, pleasesee the qslibrary.
Defaults tofalse.
When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.
Controls the maximum request body size. If this is a number, then the valuespecifies the number of bytes; if it is a string, the value is passed to thebytes library for parsing. Defaultsto'100kb'.
TheparameterLimit option controls the maximum number of parameters thatare allowed in the URL-encoded data. If a request contains more parametersthan this value, a 413 will be returned to the client. Defaults to1000.
Thetype option is used to determine what media type the middleware willparse. This option can be a string, array of strings, or a function. If nota function,type option is passed directly to thetype-is library and this canbe an extension name (likeurlencoded), a mime type (likeapplication/x-www-form-urlencoded), or a mime type with a wildcard (like*/x-www-form-urlencoded). If a function, thetype option is called asfn(req) and the request is parsed if it returns a truthy value. Defaultstoapplication/x-www-form-urlencoded.
Theverify option, if supplied, is called asverify(req, res, buf, encoding),wherebuf is aBuffer of the raw request body andencoding is theencoding of the request. The parsing can be aborted by throwing an error.
The default charset to parse as, if not specified in content-type. Must beeitherutf-8 oriso-8859-1. Defaults toutf-8.
Whether to let the value of theutf8 parameter take precedence as the charsetselector. It requires the form to contain a parameter namedutf8 with a valueof✓. Defaults tofalse.
Whether to decode numeric entities such as☺ when parsing an iso-8859-1form. Defaults tofalse.
Thedepth option is used to configure the maximum depth of theqs library whenextended istrue. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to32. It is recommended to keep this value as low as possible.
The middlewares provided by this module create errors using thehttp-errors module. The errorswill typically have astatus/statusCode property that contains the suggestedHTTP response code, anexpose property to determine if themessage propertyshould be displayed to the client, atype property to determine the type oferror without matching against themessage, and abody property containingthe read body, if available.
The following are the common errors created, though any error can come throughfor various reasons.
This error will occur when the request had aContent-Encoding header thatcontained an encoding but the "inflation" option was set tofalse. Thestatus property is set to415, thetype property is set to'encoding.unsupported', and thecharset property will be set to theencoding that is unsupported.
This error will occur when the request contained an entity that could not beparsed by the middleware. Thestatus property is set to400, thetypeproperty is set to'entity.parse.failed', and thebody property is set tothe entity value that failed parsing.
This error will occur when the request contained an entity that could not befailed verification by the definedverify option. Thestatus property isset to403, thetype property is set to'entity.verify.failed', and thebody property is set to the entity value that failed verification.
This error will occur when the request is aborted by the client before readingthe body has finished. Thereceived property will be set to the number ofbytes received before the request was aborted and theexpected property isset to the number of expected bytes. Thestatus property is set to400andtype property is set to'request.aborted'.
This error will occur when the request body's size is larger than the "limit"option. Thelimit property will be set to the byte limit and thelengthproperty will be set to the request body's length. Thestatus property isset to413 and thetype property is set to'entity.too.large'.
This error will occur when the request's length did not match the length fromtheContent-Length header. This typically occurs when the request is malformed,typically when theContent-Length header was calculated based on charactersinstead of bytes. Thestatus property is set to400 and thetype propertyis set to'request.size.invalid'.
This error will occur when something called thereq.setEncoding method priorto this middleware. This module operates directly on bytes only and you cannotcallreq.setEncoding when using this module. Thestatus property is set to500 and thetype property is set to'stream.encoding.set'.
This error will occur when the request is no longer readable when this middlewareattempts to read it. This typically means something other than a middleware fromthis module read the request body already and the middleware was also configured toread the same request. Thestatus property is set to500 and thetypeproperty is set to'stream.not.readable'.
This error will occur when the content of the request exceeds the configuredparameterLimit for theurlencoded parser. Thestatus property is set to413 and thetype property is set to'parameters.too.many'.
This error will occur when the request had a charset parameter in theContent-Type header, but theiconv-lite module does not support it OR theparser does not support it. The charset is contained in the message as wellas in thecharset property. Thestatus property is set to415, thetype property is set to'charset.unsupported', and thecharset propertyis set to the charset that is unsupported.
This error will occur when the request had aContent-Encoding header thatcontained an unsupported encoding. The encoding is contained in the messageas well as in theencoding property. Thestatus property is set to415,thetype property is set to'encoding.unsupported', and theencodingproperty is set to the encoding that is unsupported.
This error occurs when usingbodyParser.urlencoded with theextended property set totrue and the input exceeds the configureddepth option. Thestatus property is set to400. It is recommended to review thedepth option and evaluate if it requires a higher value. When thedepth option is set to32 (default value), the error will not be thrown.
This example demonstrates adding a generic JSON and URL-encoded parser as atop-level middleware, which will parse the bodies of all incoming requests.This is the simplest setup.
varexpress=require('express')varbodyParser=require('body-parser')varapp=express()// parse application/x-www-form-urlencodedapp.use(bodyParser.urlencoded())// parse application/jsonapp.use(bodyParser.json())app.use(function(req,res){res.setHeader('Content-Type','text/plain')res.write('you posted:\n')res.end(String(JSON.stringify(req.body,null,2)))})
This example demonstrates adding body parsers specifically to the routes thatneed them. In general, this is the most recommended way to use body-parser withExpress.
varexpress=require('express')varbodyParser=require('body-parser')varapp=express()// create application/json parservarjsonParser=bodyParser.json()// create application/x-www-form-urlencoded parservarurlencodedParser=bodyParser.urlencoded()// POST /login gets urlencoded bodiesapp.post('/login',urlencodedParser,function(req,res){if(!req.body||!req.body.username)res.sendStatus(400)res.send('welcome, '+req.body.username)})// POST /api/users gets JSON bodiesapp.post('/api/users',jsonParser,function(req,res){if(!req.body)res.sendStatus(400)// create user in req.body})
All the parsers accept atype option which allows you to change theContent-Type that the middleware will parse.
varexpress=require('express')varbodyParser=require('body-parser')varapp=express()// parse various different custom JSON types as JSONapp.use(bodyParser.json({type:'application/*+json'}))// parse some custom thing into a Bufferapp.use(bodyParser.raw({type:'application/vnd.custom-type'}))// parse an HTML body into a stringapp.use(bodyParser.text({type:'text/html'}))
About
Node.js body parsing middleware
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.