body-parser - npm (npmjs.com)
https://www.npmjs.com/package/body-parser
注意: body-parser 现在已经被认为是较旧的解决方案,并被 express 自带的中间件 express.json() 和 express.urlencoded() 所取代。
body-parser
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.
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:
Installation
$ npm install body-parser
API
var bodyParser = require('body-parser')
The bodyParser object exposes various factories to create middlewares. 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.
bodyParser 对象公开了各种工厂函数来创建中间件。当请求头中的 Content-Type 与 type 选项匹配时,所有中间件都会将解析后的主体填充到 req.body 属性中;如果没有要解析的主体、Content-Type 不匹配或发生错误,则填充一个空对象({})。
The various errors returned by this module are described in the errors section.
该模块返回的各种错误在错误部分中进行了描述。
bodyParser.json([options])
Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.
返回仅解析 JSON 的中间件,并且仅查看 Content-Type 请求头与 type 选项匹配的请求。此解析器接受主体的任何 Unicode 编码,并支持 gzip 和 deflate 编码的自动解压缩。
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).
中间件之后,解析后的数据会被填充到一个新的主体对象上(即 req.body)。
Options
The json function takes an optional options object that may contain any of the following keys:
inflate When set to true, then deflated (compressed) bodies will be inflated; when false, 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 will accept anything JSON.parse accepts. Defaults to true.
type The type option is used to determine what media type the middleware will parse. 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). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/json.
verify 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. The parsing can be aborted by throwing an error.
选项
json 函数接受一个可选的 options 对象,该对象可能包含以下任意键:
inflate 当设置为 true 时,压缩的主体将被解压缩;当为 false 时,压缩的主体将被拒绝。默认为 true。
limit 控制请求主体的最大大小。如果这是一个数字,则该值指定字节数;如果它是一个字符串,则该值将被传递给 bytes 库进行解析。默认为 '100kb'。
reviver reviver 选项作为第二个参数直接传递给 JSON.parse。有关此参数的更多信息,请参阅 MDN 文档中有关 JSON.parse 的内容。
strict 当设置为 true 时,将仅接受数组和对象;当为 false 时,将接受 JSON.parse 接受的所有内容。默认为 true。
type type 选项用于确定中间件将解析哪种媒体类型。此选项可以是字符串、字符串数组或函数。如果不是函数,则 type 选项将直接传递给 type-is 库,这可以是扩展名(如 json)、MIME 类型(如 application/json)或带有通配符的 MIME 类型(如 / 或 */json)。如果是函数,则调用 type 选项作为 fn(req),如果返回真值,则解析请求。默认为 application/json。
verify 如果提供了 verify 选项,则调用为 verify(req, res, buf, encoding),其中 buf 是原始请求主体的 Buffer,encoding 是请求的编码。可以通过抛出错误来中止解析。
bodyParser.raw([options])
Returns middleware that parses all bodies as a Buffer and only looks at requests where the Content-Type header matches the type option. This parser supports automatic inflation of gzip and deflate encodings.
返回将所有主体解析为 Buffer 的中间件,并且仅查看 Content-Type 请求头与 type 选项匹配的请求。此解析器支持 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.
中间件之后,解析后的数据会被填充到一个新的主体对象上(即 req.body)。这将是主体的 Buffer 对象。
Options
The raw function takes an optional options object that may contain any of the following keys:
raw 函数接受一个可选的 options 对象,该对象可能包含以下任意键:
inflate When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true.
当设置为 true 时,压缩的主体将被解压缩;当为 false 时,压缩的主体将被拒绝。默认为 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'.
控制请求主体的最大大小。如果这是一个数字,则该值指定字节数;如果它是一个字符串,则该值将被传递给 bytes 库进行解析。默认为 '100kb'。
type The type option is used to determine what media type the middleware will parse. 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 bin), a mime type (like application/octet-stream), or a mime type with a wildcard (like / or application/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/octet-stream.
type 选项用于确定中间件将解析哪种媒体类型。此选项可以是字符串、字符串数组或函数。如果不是函数,则 type 选项将直接传递给 type-is 库,这可以是扩展名(如 bin)、MIME 类型(如 application/octet-stream)或带有通配符的 MIME 类型(如 / 或 application/*)。如果是函数,则调用 type 选项作为 fn(req),如果返回真值,则解析请求。默认为 application/octet-stream。
verify 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. The parsing can be aborted by throwing an error.
如果提供了 verify 选项,则调用为 verify(req, res, buf, encoding),其中 buf 是原始请求主体的 Buffer,encoding 是请求的编码。可以通过抛出错误来中止解析。
bodyParser.text([options])
Returns middleware that parses all bodies as a string and only looks at requests where the Content-Type header matches the type option. This parser supports automatic inflation of gzip and deflate encodings.
返回一个中间件,该中间件将所有请求体解析为字符串,并且仅查看Content-Type头部与type选项相匹配的请求。此解析器支持自动解压gzip和deflate编码。
A new body string containing the parsed data is populated on the request object after the middleware (i.e. req.body). This will be a string of the body.
经过中间件处理后,一个新的包含解析数据的字符串会被填充到请求对象上(即req.body)。这将是请求体的字符串形式。
Options
The text function takes an optional options object that may contain any of the following keys:
text函数接受一个可选的选项对象,该对象可能包含以下任何一个键:
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.
指定如果请求的Content-Type头部中没有指定字符集时,文本内容的默认字符集。默认为utf-8。
inflate
When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true.
当设置为true时,被压缩(deflate)的请求体会被解压;当设置为false时,被压缩的请求体会被拒绝。默认为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'.
控制请求体的最大大小。如果这是一个数字,那么该值指定字节数;如果是一个字符串,该值会被传递给bytes库进行解析。默认为'100kb'。
type
The type option is used to determine what media type the middleware will parse. 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/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to text/plain.
type选项用于确定中间件将解析哪种媒体类型。这个选项可以是一个字符串、字符串数组或一个函数。如果不是函数,type选项会被直接传递给type-is库,这可以是一个扩展名(如txt),一个MIME类型(如text/plain),或一个带有通配符的MIME类型(如*/*或text/*)。如果是一个函数,type选项会被调用为fn(req),如果函数返回真值,则请求会被解析。默认为text/plain。
verify
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. The parsing can be aborted by throwing an error.
如果提供了verify选项,它会被调用为verify(req, res, buf, encoding),其中buf是原始请求体的Buffer,encoding是请求的编码。可以通过抛出错误来中止解析。
bodyParser.urlencoded([options])
Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
返回一个中间件,该中间件仅解析URL编码的请求体,并且仅查看Content-Type头部与type选项相匹配的请求。此解析器仅接受请求体的UTF-8编码,并支持自动解压gzip和deflate编码。
A new body object containing the parsed data is populated on the request object after the middleware (i.e. 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).
经过中间件处理后,一个新的包含解析数据的对象会被填充到请求对象上(即req.body)。这个对象将包含键值对,其中值可以是字符串或数组(当extended为false时),或者是任何类型(当extended为true时)。
Options
The urlencoded function takes an optional options object that may contain any of the following keys:
urlencoded函数接受一个可选的选项对象,该对象可能包含以下任何一个键:
extended
The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when 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. For more information, please see the qs library.
extended选项允许选择在解析URL编码数据时使用querystring库(当为false时)还是qs库(当为true时)。“extended”语法允许将丰富的对象和数组编码到URL编码格式中,从而在使用URL编码时获得类似JSON的体验。有关更多信息,请参阅qs库。
Defaults to true, but using the default has been deprecated. Please research into the difference between qs and querystring and choose the appropriate setting.
默认为true,但使用默认值已被弃用。请研究qs和querystring之间的区别,并选择适当的设置。
inflate
When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true.
当设置为true时,被压缩(deflate)的请求体会被解压;当设置为false时,被压缩的请求体会被拒绝。默认为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'.
控制请求体的最大大小。如果这是一个数字,那么该值指定字节数;如果是一个字符串,该值会被传递给bytes库进行解析。默认为'100kb'。
parameterLimit
The parameterLimit option controls the maximum number of parameters that 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 1000.
parameterLimit选项控制URL编码数据中允许的最大参数数量。如果请求包含的参数超过此值,将向客户端返回413状态码。默认为1000。
type
The type option is used to determine what media type the middleware will parse. 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 urlencoded), a mime type (like application/x-www-form-urlencoded), or a mime type with a wildcard (like */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. Defaults to application/x-www-form-urlencoded.
type选项用于确定中间件将解析哪种媒体类型。这个选项可以是一个字符串、字符串数组或一个函数。如果不是函数,type选项会被直接传递给type-is库,这可以是一个扩展名(如urlencoded),一个MIME类型(如application/x-www-form-urlencoded),或一个带有通配符的MIME类型(如*/x-www-form-urlencoded)。如果是一个函数,type选项会被调用为fn(req),如果函数返回真值,则请求会被解析。默认为application/x-www-form-urlencoded。
verify
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. The parsing can be aborted by throwing an error.
如果提供了verify选项,它会被调用为verify(req, res, buf, encoding),其中buf是原始请求体的Buffer,encoding是请求的编码。可以通过抛出错误来中止解析。
depth
The depth option is used to configure the maximum depth of the qs library when extended is true. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to 32. It is recommended to keep this value as low as possible.
depth选项用于在extended为true时配置qs库的最大深度。这允许您限制解析的键的数量,并可能有助于防止某些类型的滥用。默认为32。建议将此值保持尽可能低。
Errors
The middlewares provided by this module create errors using the http-errors module. The errors will typically have a 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.
此模块提供的中间件使用http-errors模块创建错误。这些错误通常具有一个status/statusCode属性,其中包含建议的HTTP响应代码,一个expose属性来确定是否应向客户端显示message属性,一个type属性来确定错误类型而无需匹配消息,以及一个body属性(如果可用)包含已读取的请求体。
The following are the common errors created, though any error can come through for various reasons.
以下是常见的错误,尽管由于各种原因可能会出现任何错误。
content encoding unsupported
This error will occur when the request had a Content-Encoding header that contained an encoding but the "inflation" option was set to 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.
内容编码不受支持 当请求包含Content-Encoding头部且其中包含编码,但“inflation”选项设置为false时,将发生此错误。status属性设置为415,type属性设置为'encoding.unsupported',charset属性将设置为不受支持的编码。
entity parse failed
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属性设置为解析失败的实体值。
entity verify failed
This error will occur when the request contained an entity that could not be failed verification by the defined verify option. 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.
实体验证失败 当请求包含的实体未能通过定义的verify选项验证时,将发生此错误。status属性设置为403,type属性设置为'entity.verify.failed',body属性设置为验证失败的实体值。
request aborted
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. The status property is set to 400 and type property is set to 'request.aborted'.
请求中止 当客户端在读取请求体完成之前中止请求时,将发生此错误。received属性将设置为请求中止前接收到的字节数,expected属性设置为预期字节数。status属性设置为400,type属性设置为'request.aborted'。
request entity too large
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. The status property is set to 413 and the type property is set to 'entity.too.large'.
请求实体过大 当请求体的大小超过“limit”选项时,将发生此错误。limit属性将设置为字节限制,length属性设置为请求体的长度。status属性设置为413,type属性设置为'entity.too.large'。
request size did not match content length
This error will occur when the request's length did not match the length from the Content-Length header. This typically occurs when the request is malformed, typically when the Content-Length header was calculated based on characters instead of bytes. The status property is set to 400 and the type property is set to 'request.size.invalid'.
请求大小与内容长度不匹配 当请求的长度与Content-Length头部中的长度不匹配时,将发生此错误。这通常发生在请求格式错误时,特别是当Content-Length头部是基于字符而不是字节计算时。status属性设置为400,type属性设置为'request.size.invalid'。
stream encoding should not be set
This error will occur when something called the req.setEncoding method prior to this middleware. This module operates directly on bytes only and you cannot call req.setEncoding when using this module. The status property is set to 500 and the type property is set to 'stream.encoding.set'.
流编码不应设置 当在此中间件之前调用了req.setEncoding方法时,将发生此错误。此模块直接操作字节,因此在使用此模块时不能调用req.setEncoding。status属性设置为500,type属性设置为'stream.encoding.set'。
stream is not readable
This error will occur when the request is no longer readable when this middleware attempts to read it. This typically means something other than a middleware from this module read the request body already and the middleware was also configured to read the same request. The status property is set to 500 and the type property is set to 'stream.not.readable'.
流不可读 当此中间件尝试读取请求时,请求已不可读,将发生此错误。这通常意味着除了来自此模块的中间件之外的其他内容已经读取了请求体,并且中间件也被配置为读取相同的请求。status属性设置为500,type属性设置为'stream.not.readable'。
too many parameters
This error will occur when the content of the request exceeds the configured parameterLimit for the urlencoded parser. The status property is set to 413 and the type property is set to 'parameters.too.many'.
参数过多 当请求的内容超过为urlencoded解析器配置的parameterLimit时,将发生此错误。status属性设置为413,type属性设置为'parameters.too.many'。
unsupported charset "BOGUS"
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. The charset is contained in the message as well as in the charset property. 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.
不支持的字符集“BOGUS” 当请求在Content-Type头部中包含字符集参数,但iconv-lite模块不支持它或解析器不支持它时,将发生此错误。字符集包含在消息中以及charset属性中。status属性设置为415,type属性设置为'charset.unsupported',charset属性设置为不受支持的字符集。
unsupported content encoding "bogus"
This error will occur when the request had a Content-Encoding header that contained an unsupported encoding. The encoding is contained in the message as well as in the encoding property. 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.
不支持的内容编码“bogus” 当请求包含Content-Encoding头部且其中包含不受支持的编码时,将发生此错误。编码包含在消息中以及encoding属性中。status属性设置为415,type属性设置为'encoding.unsupported',encoding属性设置为不受支持的编码。
The input exceeded the depth
This error occurs when using bodyParser.urlencoded with the extended property set to true and the input exceeds the configured depth option. The status property is set to 400. It is recommended to review the depth option and evaluate if it requires a higher value. When the depth option is set to 32 (default value), the error will not be thrown.
输入超出了深度 当使用bodyParser.urlencoded并将extended属性设置为true,且输入超过配置的depth选项时,会发生此错误。status属性设置为400。建议检查depth选项并评估是否需要更高的值。当depth选项设置为32(默认值)时,不会抛出错误。
Examples
Express/Connect top-level generic
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.
Express/Connect 顶层通用中间件
此示例展示了如何添加一个通用的 JSON 和 URL 编码解析器作为顶层中间件,该中间件将解析所有传入请求的请求体。这是最简单的设置。
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))
})
Express route-specific
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 搭配 body-parser 的最推荐方式。
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
})
Change accepted type for parsers
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' }))
274

被折叠的 条评论
为什么被折叠?



