node的bodyParser和express的urlencoded中间件有什么区别?

What is the difference between node's bodyParser and express's urlencoded middleware?

在阅读了两者之后,我仍然无法理解它, 可能是语言差异,请帮助澄清。

express.urlencoded()

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.

body-parser中间件

Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

我了解到 express.urlencoded 基于 Nodejs body-parser。 和两个页面,

https://expressjs.com/en/api.html#express.urlencoded

https://expressjs.com/en/resources/middleware/body-parser.html

甚至说同样的警告说明:

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. For example, req.body.foo.toString() may fail in multiple ways, for example foo 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,其中包含在请求正文对象中发送的参数。那么为什么我应该使用 body-parser(我必须单独安装)而不是总是使用 express.urlencoded()

我知道这不是代码问题,但我提前感谢任何可以列出主要差异的人。

so why should i use body-parser (which i have to install separatly) instead of always using express.urlencoded()

原因很简单,它在旧版本的 express 中不可用

This middleware is available in Express v4.16.0 onwards.

如果您使用的是最新版本,几乎没有理由这样做。

body-parser 提供了一些额外的实用程序,如 bodyParser.raw([options])bodyParser.text([options]),几乎没有人使用(我自己从未见过)。