Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Node.js body parsing middleware

License

NotificationsYou must be signed in to change notification settings

expressjs/body-parser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

NPM VersionNPM DownloadsBuild StatusTest CoverageOpenSSF Scorecard Badge

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:

Installation

$ npm install body-parser

API

constbodyParser=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.

bodyParser.json([options])

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).

Options

Thejson function takes an optionaloptions object that may contain any ofthe following keys:

defaultCharset

Specify the default character set for the json content if the charset is notspecified in theContent-Type header of the request. Defaults toutf-8.

inflate

When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.

limit

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'.

reviver

Thereviver option is passed directly toJSON.parse as the secondargument. You can find more information on this argumentin the MDN documentation about JSON.parse.

strict

When set totrue, will only accept arrays and objects; whenfalse willaccept anythingJSON.parse accepts. Defaults totrue.

type

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.

verify

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.

bodyParser.raw([options])

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.

Options

Theraw function takes an optionaloptions object that may contain any ofthe following keys:

inflate

When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.

limit

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'.

type

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.

verify

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.

bodyParser.text([options])

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.

Options

Thetext function takes an optionaloptions object that may contain any ofthe following keys:

defaultCharset

Specify the default character set for the text content if the charset is notspecified in theContent-Type header of the request. Defaults toutf-8.

inflate

When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.

limit

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'.

type

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.

verify

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.

bodyParser.urlencoded([options])

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).

Options

Theurlencoded function takes an optionaloptions object that may containany of the following keys:

extended

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.

inflate

When set totrue, then deflated (compressed) bodies will be inflated; whenfalse, deflated bodies are rejected. Defaults totrue.

limit

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'.

parameterLimit

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.

type

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.

verify

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.

defaultCharset

The default charset to parse as, if not specified in content-type. Must beeitherutf-8 oriso-8859-1. Defaults toutf-8.

charsetSentinel

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.

interpretNumericEntities

Whether to decode numeric entities such as☺ when parsing an iso-8859-1form. Defaults tofalse.

depth

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.

Errors

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.

content encoding unsupported

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.

entity parse failed

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.

entity verify failed

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.

request aborted

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'.

request entity too large

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'.

request size did not match content length

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'.

stream encoding should not be set

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'.

stream is not readable

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'.

too many parameters

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'.

unsupported charset "BOGUS"

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.

unsupported content encoding "bogus"

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.

The input exceeded the depth

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.

Examples

Express/Connect top-level generic

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.

constexpress=require('express')constbodyParser=require('body-parser')constapp=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)))})

Express route-specific

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.

constexpress=require('express')constbodyParser=require('body-parser')constapp=express()// create application/json parserconstjsonParser=bodyParser.json()// create application/x-www-form-urlencoded parserconsturlencodedParser=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})

Change accepted type for parsers

All the parsers accept atype option which allows you to change theContent-Type that the middleware will parse.

constexpress=require('express')constbodyParser=require('body-parser')constapp=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'}))

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp