body-parser 中间件
Node.js 请求体解析中间件。
🌐 Node.js body parsing middleware.
在你的处理程序之前,在中间件中解析传入的请求体,可通过 req.body 属性访问。
🌐 Parse incoming request bodies in a middleware before your handlers, available
under the req.body property.
注意 由于 req.body 的形状基于用户控制的输入,因此该对象中的所有属性和值都是不可信的,在信任之前应进行验证。例如,req.body.foo.toString() 可能会以多种方式失败,例如 foo 属性可能不存在,或者可能不是字符串,而 toString 可能不是函数,而是字符串或其他用户输入。
这不处理多部分主体,因为它们复杂且通常很大。对于多部分主体,你可能会对以下模块感兴趣:
🌐 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-parseryarn add body-parserpnpm add body-parserbun add body-parserNote
body-parser 不包含其自身的 TypeScript 类型定义。如果你使用 TypeScript,还需要作为开发依赖从 DefinitelyTyped 安装社区维护的类型:
npm install --save-dev @types/body-parseryarn add --dev @types/body-parserpnpm add --save-dev @types/body-parserbun add --dev @types/body-parserAPI
// Import all parsersconst bodyParser = require('body-parser');
// Or import individual parsers directlyconst json = require('body-parser/json');const urlencoded = require('body-parser/urlencoded');const raw = require('body-parser/raw');const text = require('body-parser/text');bodyParser 对象提供了各种工厂来创建中间件。所有中间件在 Content-Type 请求头与 type 选项匹配时,都会将解析后的主体填充到 req.body 属性中。
🌐 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.
此模块返回的各种错误在错误部分中进行了说明。
🌐 The various errors returned by this module are described in the errors section.
bodyParser.json([options])
返回中间件,该中间件仅解析 json,并且仅查看 Content-Type 头与 type 选项匹配的请求。此解析器接受正文的任何 Unicode 编码,并支持自动解压 gzip、br(brotli)和 deflate 编码。
🌐 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,
br (brotli) and deflate encodings.
在中间件(即 req.body``)之后,解析的数据会被填充到 request对象上的新的body` 对象中。
🌐 A new body object containing the parsed data is populated on the request
object after the middleware (i.e. req.body).
选项
🌐 Options
json 函数接受一个可选的 options 对象,该对象可能包含以下任意键:
🌐 The json function takes an optional options object that may contain any of
the following keys:
defaultCharset
如果请求的 Content-Type 头中未指定字符集,请指定 JSON 内容的默认字符集。默认值为 utf-8。
🌐 Specify the default character set for the json content if the charset is not
specified in the Content-Type header of the request. Defaults to utf-8.
inflate
当设置为 true 时,被压缩(压缩)的主体将被解压;当设置为 false 时,压缩的主体将被拒绝。默认值为 true。
🌐 When set to true, then deflated (compressed) bodies will be inflated; when
false, deflated bodies are rejected. Defaults to true.
limit
控制最大请求体大小。如果这是一个数字,则该值指定字节数;如果是一个字符串,则该值传递给 bytes 库进行解析。默认值为 '100kb'。
🌐 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'.
建议不要配置非常高的限制,并尽可能使用默认值。允许更大的负载会增加内存使用,因为解码和转换所需的资源会更多,同时处理更多数据可能导致响应时间延长。所谓“非常高”,是指高于默认值的数值,例如负载为 5 MB 或更大时,可能会出现这些风险。使用默认限制时,这些问题不会发生。
reviver
reviver 选项作为第二个参数直接传递给 JSON.parse。你可以在 关于 JSON.parse 的 MDN 文档 中找到有关此参数的更多信息。
🌐 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
当设置为 true 时,只接受数组和对象;当设置为 false 时,将接受 JSON.parse 接受的任何内容。默认值为 true。
🌐 When set to true, will only accept arrays and objects; when false will
accept anything JSON.parse accepts. Defaults to true.
type
type 选项用于确定中间件将解析的媒体类型。该选项可以是一个字符串、字符串数组或一个函数。如果不是函数,type 选项将直接传递给 type-is 库,并且可以是一个扩展名(如 json)、一个 mime 类型(如 application/json),或带有通配符的 mime 类型(如 */* 或 */json)。如果是函数,则 type 选项会被调用为 fn(req),并且如果返回真值,则请求会被解析。默认值为 application/json。
🌐 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
verify 选项,如果提供,会作为 verify(req, res, buf, encoding) 调用,其中 buf 是原始请求体的 Buffer,encoding 是请求的编码。通过抛出错误可以中止解析。
🌐 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.
bodyParser.raw([options])
返回中间件,该中间件将所有请求体解析为 Buffer,并且仅查看 Content-Type 头部与 type 选项匹配的请求。此解析器支持自动解压 gzip、br(brotli)和 deflate 编码。
🌐 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, br (brotli) and deflate
encodings.
一个包含解析数据的新 body 对象会在中间件(即 req.body``)之后被填充到 request对象上。这将是一个Buffer` 对象的主体。
🌐 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.
选项
🌐 Options
raw 函数接受一个可选的 options 对象,该对象可能包含以下任意键:
🌐 The raw function takes an optional options object that may contain any of
the following keys:
inflate
当设置为 true 时,被压缩(压缩)的主体将被解压;当设置为 false 时,压缩的主体将被拒绝。默认值为 true。
🌐 When set to true, then deflated (compressed) bodies will be inflated; when
false, deflated bodies are rejected. Defaults to true.
limit
控制最大请求体大小。如果这是一个数字,则该值指定字节数;如果是一个字符串,则该值传递给 bytes 库进行解析。默认值为 '100kb'。
🌐 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'.
建议不要配置非常高的限制,并尽可能使用默认值。允许更大的负载会增加内存使用,因为解码和转换所需的资源会更多,同时处理更多数据可能导致响应时间延长。所谓“非常高”,是指高于默认值的数值,例如负载为 5 MB 或更大时,可能会出现这些风险。使用默认限制时,这些问题不会发生。
type
type 选项用于确定中间件将解析的媒体类型。该选项可以是一个字符串、字符串数组或一个函数。如果不是函数,type 选项将直接传递给 type-is 库,并且可以是一个扩展名(如 bin)、一个 mime 类型(如 application/octet-stream),或带有通配符的 mime 类型(如 */* 或 application/*)。如果是函数,则 type 选项会被调用为 fn(req),并且如果返回真值,则请求会被解析。默认值为 application/octet-stream。
🌐 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.
verify
verify 选项,如果提供,会作为 verify(req, res, buf, encoding) 调用,其中 buf 是原始请求体的 Buffer,encoding 是请求的编码。通过抛出错误可以中止解析。
🌐 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.
bodyParser.text([options])
返回中间件,该中间件将所有请求体解析为字符串,并且仅查看 Content-Type 头与 type 选项匹配的请求。该解析器支持自动解压 gzip、br(brotli)和 `deflate“ 编码。
🌐 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, br (brotli) and deflate
encodings.
在中间件(即 req.body``)之后,解析的数据会被填充到 request对象上的新的body` 字符串中。这将是一个包含正文的字符串。
🌐 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.
选项
🌐 Options
text 函数接受一个可选的 options 对象,该对象可能包含以下任意键:
🌐 The text function takes an optional options object that may contain any of
the following keys:
defaultCharset
如果请求的 Content-Type 头中未指定字符集,请指定文本内容的默认字符集。默认值为 utf-8。
🌐 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
当设置为 true 时,被压缩(压缩)的主体将被解压;当设置为 false 时,压缩的主体将被拒绝。默认值为 true。
🌐 When set to true, then deflated (compressed) bodies will be inflated; when
false, deflated bodies are rejected. Defaults to true.
limit
控制最大请求体大小。如果这是一个数字,则该值指定字节数;如果是一个字符串,则该值传递给 bytes 库进行解析。默认值为 '100kb'。
🌐 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'.
建议不要配置非常高的限制,并尽可能使用默认值。允许更大的负载会增加内存使用,因为解码和转换所需的资源会更多,同时处理更多数据可能导致响应时间延长。所谓“非常高”,是指高于默认值的数值,例如负载为 5 MB 或更大时,可能会出现这些风险。使用默认限制时,这些问题不会发生。
type
type 选项用于确定中间件将解析哪种媒体类型。此选项可以是字符串、字符串数组或函数。如果不是函数,则 type 选项会直接传递给 type-is 库,这可以是扩展名(例如 txt)、MIME 类型(例如 text/plain),或者带有通配符的 MIME 类型(例如 */* 或 text/*)。如果是函数,则在作为 fn(req) 调用 type 选项时,如果返回值为真,则请求将被解析。默认值为 text/plain。
🌐 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.
verify
verify 选项,如果提供,会作为 verify(req, res, buf, encoding) 调用,其中 buf 是原始请求体的 Buffer,encoding 是请求的编码。通过抛出错误可以中止解析。
🌐 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.
bodyParser.urlencoded([options])
返回只解析 urlencoded 请求体的中间件,并且只查看 Content-Type 头与 type 选项匹配的请求。该解析器只接受请求体的 UTF-8 和 ISO-8859-1 编码,并支持自动解压 gzip、br(brotli)和 deflate 编码。
🌐 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 and ISO-8859-1 encodings of the body and supports
automatic inflation of gzip, br (brotli) and deflate encodings.
在中间件(即 req.body``)之后,解析后的数据会填充到 request对象上的一个新的body对象中。这个对象将包含键值对,其中值可以是字符串或数组(当extended为false时),或者是任意类型(当extended为true` 时)。
🌐 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).
选项
🌐 Options
urlencoded 函数接受一个可选的 options 对象,该对象可能包含以下任意键:
🌐 The urlencoded function takes an optional options object that may contain
any of the following keys:
extended
“扩展”语法允许将丰富的对象和数组编码为 URL 编码格式,从而实现类似 JSON 的 URL 编码体验。更多信息,请参见 qs 库。
🌐 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.
默认为 false。
🌐 Defaults to false.
inflate
当设置为 true 时,被压缩(压缩)的主体将被解压;当设置为 false 时,压缩的主体将被拒绝。默认值为 true。
🌐 When set to true, then deflated (compressed) bodies will be inflated; when
false, deflated bodies are rejected. Defaults to true.
limit
控制最大请求体大小。如果这是一个数字,则该值指定字节数;如果是一个字符串,则该值传递给 bytes 库进行解析。默认值为 '100kb'。
🌐 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'.
建议不要配置非常高的限制,并尽可能使用默认值。允许更大的负载会增加内存使用,因为解码和转换所需的资源会更多,同时处理更多数据可能导致响应时间延长。所谓“非常高”,是指高于默认值的数值,例如负载为 5 MB 或更大时,可能会出现这些风险。使用默认限制时,这些问题不会发生。
parameterLimit
parameterLimit 选项控制允许在 URL 编码数据中使用的最大参数数量。如果请求包含的参数超过此值,将向客户端返回 413。默认值为 1000。
🌐 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.
type
type选项用于确定中间件将解析哪种媒体类型。该选项可以是字符串、字符串数组或函数。如果不是函数,type选项会直接传递给type-is库,这可以是扩展名(如urlencoded)、MIME类型(如application/x-www-form-urlencoded)或带通配符的MIME类型(如*/x-www-form-urlencoded)。如果是函数,则type选项将以fn(req)的方式调用,并在返回真值时解析请求。默认值为application/x-www-form-urlencoded。
🌐 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.
verify
verify 选项,如果提供,会作为 verify(req, res, buf, encoding) 调用,其中 buf 是原始请求体的 Buffer,encoding 是请求的编码。通过抛出错误可以中止解析。
🌐 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.
defaultCharset
如果内容类型中未指定,则默认解析的字符集。必须是 utf-8 或 iso-8859-1。默认为 utf-8。
🌐 The default charset to parse as, if not specified in content-type. Must be
either utf-8 or iso-8859-1. Defaults to utf-8.
charsetSentinel
是否让 utf8 参数的值作为字符集选择器优先。它要求表单包含一个名为 utf8 且值为 ✓ 的参数。默认值为 false。
🌐 Whether to let the value of the utf8 parameter take precedence as the charset
selector. It requires the form to contain a parameter named utf8 with a value
of ✓. Defaults to false.
interpretNumericEntities
在解析 iso-8859-1 表单时,是否解码诸如 ☺ 的数字实体。默认值为 false。
🌐 Whether to decode numeric entities such as ☺ when parsing an iso-8859-1
form. Defaults to false.
depth
depth 选项用于在 extended 为 true 时配置 qs 库的最大深度。这允许你限制被解析的键的数量,并且对于防止某些类型的滥用很有用。默认值为 32。建议将此值保持在尽可能低的水平。
🌐 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.
错误
🌐 Errors
该模块提供的中间件使用http-errors模块创建错误。这些错误通常具有一个status/statusCode属性,包含建议的HTTP响应代码,一个expose属性用于确定message属性是否应显示给客户端,一个type属性用于在不匹配message的情况下确定错误类型,以及一个body属性,包含可读取的主体(如果有的话)。
🌐 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.
以下是常见的错误,尽管任何错误都可能由于各种原因出现。
🌐 The following are the common errors created, though any error can come through for various reasons.
不支持的内容编码
🌐 content encoding unsupported
当请求包含一个带有编码的 Content-Encoding 头部,但“解压”选项被设置为 false 时,将会发生此错误。status 属性被设置为 415,type 属性被设置为 'encoding.unsupported',而 charset 属性将被设置为不受支持的编码。
🌐 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.
实体解析失败
🌐 entity parse failed
当请求包含中间件无法解析的实体时,将会发生此错误。status 属性设置为 400,type 属性设置为 'entity.parse.failed',body 属性设置为解析失败的实体值。
🌐 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.
实体验证失败
🌐 entity verify failed
当请求包含一个无法通过定义的 verify 选项验证的实体时,将发生此错误。status 属性被设置为 403,type 属性被设置为 'entity.verify.failed',body 属性被设置为验证失败的实体值。
🌐 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.
请求已中止
🌐 request aborted
当客户端在读取完请求体之前中止请求时,将会发生此错误。received 属性将被设置为请求被中止前接收到的字节数,expected 属性将被设置为预期字节数。status 属性被设置为 400,type 属性被设置为 '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'.
请求实体过大
🌐 request entity too large
当请求主体的大小超过“limit”选项时,将发生此错误。limit 属性将设置为字节限制,length 属性将设置为请求主体的长度。status 属性设置为 413,type 属性设置为 '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'.
请求大小与内容长度不匹配
🌐 request size did not match content length
当请求的长度与 Content-Length 头中的长度不匹配时,会发生此错误。这通常发生在请求格式错误时,通常是因为 Content-Length 头是基于字符而不是字节计算的。status 属性被设置为 400,type 属性被设置为 'request.size.invalid'。
🌐 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'.
不应设置流编码
🌐 stream encoding should not be set
当在此中间件之前调用称为 req.setEncoding 的方法时,会发生此错误。该模块仅直接操作字节,并且在使用此模块时不能调用 req.setEncoding。status 属性被设置为 500,而 type 属性被设置为 'stream.encoding.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'.
流不可读
🌐 stream is not readable
当此中间件尝试读取请求时,如果请求无法再被读取,就会发生此错误。这通常意味着除了来自此模块的中间件之外,还有其他中间件已经读取了请求主体,而该中间件也被配置为读取相同的请求。status 属性被设置为 500,type 属性被设置为 'stream.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'.
参数太多
🌐 too many parameters
当请求的内容超过为 urlencoded 解析器配置的 parameterLimit 时,将会发生此错误。status 属性设置为 413,type 属性设置为 'parameters.too.many'。
🌐 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'.
不支持的字符集 “BOGUS”
🌐 unsupported charset “BOGUS”
当请求在 Content-Type 头中包含字符集参数,但 iconv-lite 模块不支持它或解析器不支持它时,会发生此错误。字符集包含在消息中以及 charset 属性中。status 属性被设置为 415,type 属性被设置为 'charset.unsupported',而 charset 属性被设置为不支持的字符集。
🌐 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”
🌐 unsupported content encoding “bogus”
当请求包含不支持的编码的 Content-Encoding 头时,将会发生此错误。编码信息包含在消息中,也包含在 encoding 属性中。status 属性设置为 415,type 属性设置为 'encoding.unsupported',并且 encoding 属性设置为不支持的编码。
🌐 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.
输入超出了深度
🌐 The input exceeded the depth
当使用 bodyParser.urlencoded 并且 extended 属性设置为 true 且输入超出配置的 depth 选项时,会发生此错误。status 属性设置为 400。建议检查 depth 选项,并评估是否需要更高的值。当 depth 选项设置为 32(默认值)时,将不会抛出该错误。
🌐 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.
例子
🌐 Examples
表达/连接顶层泛型
🌐 Express/Connect top-level generic
此示例演示了将通用的 JSON 和 URL 编码解析器作为顶层中间件添加,它将解析所有传入请求的主体。这是最简单的设置。
🌐 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.
const express = require('express');const bodyParser = require('body-parser');
const app = 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
这个例子演示了如何将 body 解析器专门添加到需要它们的路由中。一般来说,这也是推荐用于 Express 的 body-parser 的最常用方式。
🌐 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.
const express = require('express');const bodyParser = require('body-parser');
const app = express();
// create application/json parserconst jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parserconst urlencodedParser = 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
所有解析器都接受一个 type 选项,它允许你更改中间件将解析的 Content-Type。
🌐 All the parsers accept a type option which allows you to change the
Content-Type that the middleware will parse.
const express = require('express');const bodyParser = require('body-parser');
const app = 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