body-parser

NPM Version NPM Downloads Build Status Test Coverage

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:您可能感兴趣的其他主体解析器:

Installation安装

$ npm install body-parser

API

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.错误部分描述了此模块返回的各种错误。

bodyParser.json([options])

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 gzip and deflate encodings.此解析器接受正文的任何Unicode编码,并支持自动扩展gzipdeflate编码。

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

Options

The json function takes an optional options object that may contain any of the following keys:json函数接受一个可选的选项对象,该对象可能包含以下任意键:

inflate

When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. 当设置为true时,放气(压缩)的主体将充气;如果为false,则会拒绝放气主体。Defaults to true.默认为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'.默认值为'100kb'

reviver

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文档中找到有关此参数的更多信息。

strict

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

type

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

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. 如果提供了verify选项,则以verify(req, res, buf, encoding)的形式调用,其中buf是原始请求主体的缓冲区,encoding是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。

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. 返回中间件,该中间件将所有主体解析为缓冲区,并仅查看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)。这将是主体的缓冲对象。

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. 当设置为true时,放气(压缩)的物体将充气;如果为false,则会拒绝放气实体。Defaults to true.默认为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'.默认值为'100kb'

type

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

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. 如果提供了verify选项,则以verify(req, res, buf, encoding)的形式调用,其中buf是原始请求主体的Bufferencoding是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。

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. 返回中间件,该中间件将所有正文解析为字符串,并仅查看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.这将是身体的一串。

Options

The text function takes an optional options object that may contain any of the following keys:text函数采用可选options对象,该对象可能包含以下任意键:

defaultCharset

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

inflate

When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. 当设置为true时,放气(压缩)的物体将充气;如果为false,则会拒绝放气实体。Defaults to true默认值为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'默认值为'100kb'

type

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

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. 如果提供了verify选项,则以verify(req, res, buf, encoding)的形式调用,其中buf是原始请求主体的Bufferencoding是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。

bodyParser.urlencoded([options])

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 gzip and deflate encodings.该解析器只接受主体的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). 包含解析数据的新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时)。

Options

The urlencoded function takes an optional options object that may contain any of the following keys:urlencoded函数采用可选options对象,该对象可能包含以下任意键:

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). 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.请研究qsquerystring之间的差异,并选择适当的设置。

inflate

When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. 当设置为true时,放气(压缩)的物体将充气;如果为false,则会拒绝放气实体。Defaults to true默认值为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'默认值为'100kb'

parameterLimit

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

type

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 urlencoded), a mime type (like application/x-www-form-urlencoded), or a mime type with a wildcard (like */x-www-form-urlencoded). 如果不是函数,类型选项将直接传递给type-is库,它可以是扩展名(如urlencoded)、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

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. 如果提供了验证选项,则以verify(req, res, buf, encoding)的形式调用,其中buf是原始请求主体的Bufferencoding是请求的编码。The parsing can be aborted by throwing an error.可以通过抛出错误中止解析。

Errors

The middlewares provided by this module create errors using the http-errors module. 此模块提供的中间件使用http-errors模块创建错误。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响应代码的status/statusCode属性、一个用于确定是否应向客户端显示消息属性的expose属性、一个用于确定错误类型而不与消息匹配的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. 当请求的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属性将设置为不受支持的编码。

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属性设置为400type属性设置为'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. 当请求包含无法通过定义的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属性设置为403type属性设置为'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. received属性将设置为请求中止前接收的字节数,expected属性将设置为需要的字节数。The status property is set to 400 and type property is set to 'request.aborted'.status属性设置为400type属性设置为'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. limit属性将设置为字节限制,length属性将设置为请求正文的长度。The status property is set to 413 and the type property is set to 'entity.too.large'.status属性设置为413type属性设置为'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. 当请求的长度与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属性设置为400type属性设置为'request.size.invalid'

stream encoding should not be set不应设置流编码

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.setEncodingThe status property is set to 500 and the type property is set to 'stream.encoding.set'.status属性设置为500type属性设置为'stream.encoding.set'

too many parameters参数太多

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属性设置为413type属性设置为'parameters.too.many'

unsupported charset "BOGUS"不支持的字符集“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. 当请求的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属性设置为415type属性设置为'charset.unsupported'charset属性设置为不受支持的字符集。

unsupported content encoding "bogus"不支持的内容编码“bogus”

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属性设置为415type属性设置为'encoding.unsupported',编码属性设置为不受支持的编码。

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. 此示例演示如何添加一个通用的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))
})

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一起使用的最推荐方法。

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' }))

License许可证

MIT