Node.js body parsing middleware.Node.js主体解析中间件。
Parse incoming request bodies in a middleware before your handlers, available under the 在处理程序之前解析中间件中的传入请求主体,可在req.body
property.req.body
属性下使用。
Note As 由于req.body
's shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. req.body
的形状基于用户控制的输入,因此此对象中的所有属性和值都不受信任,应在信任之前进行验证。For example, 例如,req.body.foo.toString()
may fail in multiple ways, for example the foo
property may not be there or may not be a string, and toString
may not be a function and instead a string or other user input.req.body.foo.toString()
可能以多种方式失败,例如,foo
属性可能不存在或可能不是字符串,而toString
可能不是函数,而是字符串或其他用户输入。
Learn about the anatomy of an HTTP transaction in Node.js.了解Node.js中HTTP事务的剖析。
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:对于多部分实体,您可能对以下模块感兴趣:
This module provides the following parsers:此模块提供以下解析器:
Other body parsers you might be interested in:您可能感兴趣的其他主体解析器:
$ npm install body-parser
var bodyParser = require('body-parser')
The bodyParser
object exposes various factories to create middlewares. bodyParser
对象公开各种工厂来创建中间件。All middlewares will populate the 当req.body
property with the parsed body when the Content-Type
request header matches the type
option, or an empty object ({}
) if there was no body to parse, the Content-Type
was not matched, or an error occurred.Content-Type
请求头与type
选项匹配时,所有中间件都将使用解析的主体填充req.body
属性;如果没有要解析的主体、内容类型不匹配或发生错误,则使用空对象({}
)。
The various errors returned by this module are described in the errors section.错误部分描述了此模块返回的各种错误。
Returns middleware that only parses 返回仅解析json
and only looks at requests where the Content-Type
header matches the type
option. json
并仅查看Content-Type
标头与类型选项匹配的请求的中间件。This parser accepts any Unicode encoding of the body and supports automatic inflation of 此解析器接受正文的任何Unicode编码,并支持自动扩展gzip
and deflate
encodings.gzip
和deflate
编码。
A new 包含解析数据的新body
object containing the parsed data is populated on the request
object after the middleware (i.e. req.body
).body
对象填充在中间件之后的request
对象上(即req.body
)。
The json
function takes an optional options
object that may contain any of the following keys:json
函数接受一个可选的选项对象,该对象可能包含以下任意键:
When set to 当设置为true
, then deflated (compressed) bodies will be inflated; when false
, deflated bodies are rejected. true
时,放气(压缩)的主体将充气;如果为false
,则会拒绝放气主体。Defaults to 默认为true
.true
。
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'
.'100kb'
。
The reviver
option is passed directly to JSON.parse
as the second argument. reviver
选项作为直接传递给JSON.parse
的第二个参数。You can find more information on this argument in the MDN documentation about JSON.parse.您可以在关于JSON.parse的MDN文档中找到有关此参数的更多信息。
When set to 设置为true
, will only accept arrays and objects; when false
will accept anything JSON.parse
accepts. Defaults to true
.true
时,将仅接受数组和对象;如果为false
,则将接受JSON.parse
接受的任何内容。默认为true
。
The type
option is used to determine what media type the middleware will parse. type
选项用于确定中间件将解析的媒体类型。This option can be a string, array of strings, or a function. 此选项可以是字符串、字符串数组或函数。If not a function, 如果不是函数,type
option is passed directly to the type-is library and this can be an extension name (like json
), a mime type (like application/json
), or a mime type with a wildcard (like */*
or */json
). type
选项将直接传递给type-is库,它可以是扩展名(如json
)、mime类型(如application/json
)或带有通配符的mime类型(如*/*
或*/json
)。If a function, the 如果是函数,则type
option is called as fn(req)
and the request is parsed if it returns a truthy value. type
选项以fn(req)
的形式调用,如果返回truthy值,则解析请求。Defaults to 默认为application/json
.application/json
。
The 如果提供了verify
option, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. verify
选项,则以verify(req, res, buf, encoding)
的形式调用,其中buf
是原始请求主体的缓冲区,encoding
是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。
Returns middleware that parses all bodies as a 返回中间件,该中间件将所有主体解析为缓冲区,并仅查看Buffer
and only looks at requests where the Content-Type
header matches the type
option. Content-Type
标头与type
选项匹配的请求。This parser supports automatic inflation of 该解析器支持gzip
and deflate
encodings.gzip
的自动膨胀和deflate
编码。
A new 包含解析数据的新body
object containing the parsed data is populated on the request
object after the middleware (i.e. req.body
). This will be a Buffer
object of the body.body
对象填充在中间件之后的request
对象上(即req.body
)。这将是主体的缓冲对象。
The raw
function takes an optional options
object that may contain any of the following keys:raw
函数接受一个可选options
对象,该对象可能包含以下任意键:
When set to 当设置为true
, then deflated (compressed) bodies will be inflated; when false
, deflated bodies are rejected. true
时,放气(压缩)的物体将充气;如果为false
,则会拒绝放气实体。Defaults to 默认为true
.true
。
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'
.'100kb'
。
The type
option is used to determine what media type the middleware will parse. type
选项用于确定中间件将解析的媒体类型。This option can be a string, array of strings, or a function. 此选项可以是字符串、字符串数组或函数。If not a function, 如果不是函数,type
option is passed directly to the type-is library and this can be an extension name (like json
), a mime type (like application/json
), or a mime type with a wildcard (like */*
or */json
). type
选项将直接传递给type-is库,它可以是扩展名(如json
)、mime类型(如application/json
)或带有通配符的mime类型(如*/*
或*/json
)。If a function, the 如果是函数,则type
option is called as fn(req)
and the request is parsed if it returns a truthy value. type
选项以fn(req)
的形式调用,如果返回truthy值,则解析请求。Defaults to 默认值为application/octet-stream
application/octet-stream
。
The 如果提供了verify
option, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. verify
选项,则以verify(req, res, buf, encoding)
的形式调用,其中buf
是原始请求主体的Buffer
,encoding
是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。
Returns middleware that parses all bodies as a string and only looks at requests where the 返回中间件,该中间件将所有正文解析为字符串,并仅查看Content-Type
header matches the type
option. Content-Type
标头与type
选项匹配的请求。This parser supports automatic inflation of 该解析器支持gzip
and deflate
encodings.gzip
的自动膨胀和deflate
编码。
A new 包含解析数据的新body
string containing the parsed data is populated on the request
object after the middleware (i.e. req.body
). body
字符串填充在中间件之后的request
对象上(即req.body
)。This will be a string of the body.这将是身体的一串。
The text
function takes an optional options
object that may contain any of the following keys:text
函数采用可选options
对象,该对象可能包含以下任意键:
Specify the default character set for the text content if the charset is not specified in the 如果在请求的Content-Type
header of the request. Content-Type
标头中未指定字符集,请指定文本内容的默认字符集。Defaults to 默认值为utf-8
utf-8
。
When set to 当设置为true
, then deflated (compressed) bodies will be inflated; when false
, deflated bodies are rejected. true
时,放气(压缩)的物体将充气;如果为false
,则会拒绝放气实体。Defaults to 默认值为true
true
。
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'
'100kb'
。
The type
option is used to determine what media type the middleware will parse. type
选项用于确定中间件将解析的媒体类型。This option can be a string, array of strings, or a function. 此选项可以是字符串、字符串数组或函数。If not a function, 如果不是函数,type
option is passed directly to the type-is library and this can be an extension name (like txt
), a mime type (like text/plain
), or a mime type with a wildcard (like */*
or text/*
). type
选项将直接传递给type-is库,它可以是扩展名(如txt
)、mime类型(如text/plain
)或带有通配符的mime类型(如*/*
或text/*
)。If a function, the 如果是函数,则type
option is called as fn(req)
and the request is parsed if it returns a truthy value. type
选项以fn(req)
的形式调用,如果返回truthy值,则解析请求。Defaults to 默认值为text/plain
text/plain
。
The 如果提供了verify
option, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. verify
选项,则以verify(req, res, buf, encoding)
的形式调用,其中buf
是原始请求主体的Buffer
,encoding
是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。
Returns middleware that only parses 返回中间件,该中间件仅解析urlencoded
bodies and only looks at requests where the Content-Type
header matches the type
option. urlencoded
主体,并仅查看Content-Type
标头与type
选项匹配的请求。This parser accepts only UTF-8 encoding of the body and supports automatic inflation of 该解析器只接受主体的UTF-8编码,并支持gzip
and deflate
encodings.gzip
的自动膨胀和deflate
编码。
A new 包含解析数据的新body
object containing the parsed data is populated on the request
object after the middleware (i.e. req.body
). body
对象填充在中间件之后的request
对象上(即req.body
)。This object will contain key-value pairs, where the value can be a string or array (when 此对象将包含键值对,其中值可以是字符串或数组(扩展为extended
is false
), or any type (when extended
is true
).false
时)或任何类型(扩展为true
时)。
The urlencoded
function takes an optional options
object that may contain any of the following keys:urlencoded
函数采用可选options
对象,该对象可能包含以下任意键:
The extended
option allows to choose between parsing the URL-encoded data with the querystring
library (when false
) or the qs
library (when true
). extended
允许在使用querystring
库解析URL编码数据(如果为false
)或使用qs库解析URL编码数据(如果为true
)之间进行选择。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. “扩展”语法允许将丰富的对象和数组编码为URL编码格式,从而实现类似JSON的URL编码体验。For more information, please see the qs library.有关更多信息,请参阅qs库。
Defaults to 默认值为true
, but using the default has been deprecated. true
,但已不推荐使用默认值。Please research into the difference between 请研究qs
and querystring
and choose the appropriate setting.qs
和querystring
之间的差异,并选择适当的设置。
When set to 当设置为true
, then deflated (compressed) bodies will be inflated; when false
, deflated bodies are rejected. true
时,放气(压缩)的物体将充气;如果为false
,则会拒绝放气实体。Defaults to 默认值为true
true
。
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'
'100kb'
。
The parameterLimit
option controls the maximum number of parameters that are allowed in the URL-encoded data. parameterLimit
选项控制URL编码数据中允许的最大参数数。If a request contains more parameters than this value, a 413 will be returned to the client. 如果请求包含的参数多于此值,则将向客户端返回413。Defaults to 默认值为1000
1000
。
The type
option is used to determine what media type the middleware will parse. type
选项用于确定中间件将解析的媒体类型。This option can be a string, array of strings, or a function. 此选项可以是字符串、字符串数组或函数。If not a function, 如果不是函数,类型选项将直接传递给type-is库,它可以是扩展名(如type
option is passed directly to the type-is library and this can be an extension name (like urlencoded
), a mime type (like application/x-www-form-urlencoded
), or a mime type with a wildcard (like */x-www-form-urlencoded
). urlencode
d)、mime类型(如application/x-www-form-urlencoded
)或带有通配符的mime类型(如*/x-www-form-urlencoded
)。If a function, the 如果是函数,则type
option is called as fn(req)
and the request is parsed if it returns a truthy value. type
选项以fn(req)
的形式调用,如果返回truthy值,则解析请求。Defaults to 默认值为application/x-www-form-urlencoded
application/x-www-form-urlencoded
。
The 如果提供了验证选项,则以verify
option, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. verify(req, res, buf, encoding)
的形式调用,其中buf
是原始请求主体的Buffer
,encoding
是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。
The middlewares provided by this module create errors using the 此模块提供的中间件使用http-errors
module. http-errors
模块创建错误。The errors will typically have a 这些错误通常具有一个包含建议的HTTP响应代码的status
/statusCode
property that contains the suggested HTTP response code, an expose
property to determine if the message
property should be displayed to the client, a type
property to determine the type of error without matching against the message
, and a body
property containing the read body, if available.status
/statusCode
属性、一个用于确定是否应向客户端显示消息属性的expose
属性、一个用于确定错误类型而不与消息匹配的type
属性,以及一个包含读正文的body
属性(如果可用)。
The following are the common errors created, though any error can come through for various reasons.以下是创建的常见错误,尽管任何错误都可能由于各种原因而出现。
This error will occur when the request had a 当请求的Content-Encoding
header that contained an encoding but the "inflation" option was set to false
. Content-Encoding
标头包含编码,但“膨胀”选项设置为false
时,将发生此错误。The status
property is set to 415
, the type
property is set to 'encoding.unsupported'
, and the charset
property will be set to the encoding that is unsupported.status
属性设置为415,type
属性设置为'encoding.unsupported'
,charset
属性将设置为不受支持的编码。
This error will occur when the request contained an entity that could not be parsed by the middleware. 当请求包含中间件无法解析的实体时,将发生此错误。The status
property is set to 400
, the type
property is set to 'entity.parse.failed'
, and the body
property is set to the entity value that failed parsing.status
属性设置为400
,type
属性设置为'entity.parse.failed'
,body
属性设置为解析失败的实体值。
This error will occur when the request contained an entity that could not be failed verification by the defined 当请求包含无法通过定义的verify
option. verify
选项进行验证的实体时,将发生此错误。The status
property is set to 403
, the type
property is set to 'entity.verify.failed'
, and the body
property is set to the entity value that failed verification.status
属性设置为403
,type
属性设置为'entity.verify.failed'
,body
属性设置为验证失败的实体值。
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 of bytes received before the request was aborted and the expected
property is set to the number of expected bytes. received
属性将设置为请求中止前接收的字节数,expected
属性将设置为需要的字节数。The status
property is set to 400
and type
property is set to 'request.aborted'
.status
属性设置为400
,type
属性设置为'request.aborted'
。
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 length
property will be set to the request body's length. limit
属性将设置为字节限制,length
属性将设置为请求正文的长度。The status
property is set to 413
and the type
property is set to 'entity.too.large'
.status
属性设置为413
,type
属性设置为'entity.too.large'
。
This error will occur when the request's length did not match the length from the 当请求的长度与Content-Length
header. Content-Length
标头的长度不匹配时,将发生此错误。This typically occurs when the request is malformed, typically when the 这通常发生在请求格式错误时,通常是基于字符而不是字节计算Content-Length
header was calculated based on characters instead of bytes. Content-Length
头时。The status
property is set to 400
and the type
property is set to 'request.size.invalid'
.status
属性设置为400
,type
属性设置为'request.size.invalid'
。
This error will occur when something called the 此错误将在调用此中间件之前的req.setEncoding
method prior to this middleware. req.setEncoding
方法时发生。This module operates directly on bytes only and you cannot call 此模块仅直接对字节进行操作,使用此模块时不能调用req.setEncoding
when using this module. req.setEncoding
。The status
property is set to 500
and the type
property is set to 'stream.encoding.set'
.status
属性设置为500
,type
属性设置为'stream.encoding.set'
。
This error will occur when the content of the request exceeds the configured 当请求的内容超过为parameterLimit
for the urlencoded
parser. urlencoded
解析器配置的parameterLimit
时,将发生此错误。The status
property is set to 413
and the type
property is set to 'parameters.too.many'
.status
属性设置为413
,type
属性设置为'parameters.too.many'
。
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 the parser does not support it. Content-Type
标头中包含字符集参数,但iconv-lite
模块不支持该参数或解析器不支持该参数时,将发生此错误。The charset is contained in the message as well as in the 该字符集包含在消息以及charset
property. charset
属性中。The status
property is set to 415
, the type
property is set to 'charset.unsupported'
, and the charset
property is set to the charset that is unsupported.status
属性设置为415
,type
属性设置为'charset.unsupported'
,charset
属性设置为不受支持的字符集。
This error will occur when the request had a 当请求的Content-Encoding
header that contained an unsupported encoding. Content-Encoding
标头包含不受支持的编码时,将发生此错误。The encoding is contained in the message as well as in the 该编码包含在消息以及encoding
property. encoding
属性中。The status
property is set to 415
, the type
property is set to 'encoding.unsupported'
, and the encoding
property is set to the encoding that is unsupported.status
属性设置为415
,type
属性设置为'encoding.unsupported'
,编码属性设置为不受支持的编码。
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. 此示例演示如何添加一个通用的JSON和URL编码解析器作为顶级中间件,它将解析所有传入请求的主体。This is the simplest setup.这是最简单的设置。
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 recommended way to use body-parser with Express.通常,这是将主体解析器与Express一起使用的最推荐方法。
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) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
All the parsers accept a 所有解析器都接受一个type
option which allows you to change the Content-Type
that the middleware will parse.type
选项,该选项允许您更改中间件将解析的Content-Type
。
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// 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' }))