为什么我需要将 (req, res, next) 传递给 Express 中的 bodyParser?

Why do I need to pass (req, res, next) to bodyParser in Express?

我最初是这样使用 bodyParser 的:

app.use(bodyParser.json());

但是,现在我想有条件地使用 bodyParser:

app.use((req, res, next) => {
    if (req.originalUrl === '/hooks') {
        next();
    } else {
        bodyParser.json()(req, res, next);
    }
});

当我尝试删除 (req, res, next) 时,解析器不工作。即,

app.use((req, res, next) => {
    if (req.originalUrl === '/hooks') {
        next();
    } else {
        bodyParser.json();
    }
});

无效。

为什么在bodyParser.json()之后需要(req, res, next)

https://github.com/expressjs/body-parser/blob/master/index.js#L108

function bodyParser (options) {
  var opts = {}

  // exclude type option
  if (options) {
    for (var prop in options) {
      if (prop !== 'type') {
        opts[prop] = options[prop]
      }
    }
  }

  var _urlencoded = exports.urlencoded(opts)
  var _json = exports.json(opts)

  return function bodyParser (req, res, next) {
    _json(req, res, function (err) {
      if (err) return next(err)
      _urlencoded(req, res, next)
    })
  }
}

正文解析器是一个中间件,需要访问 res、req 和 next。

它使用 req 解析您的请求,为了将控制传递给下一个中间件,它需要访问下一个函数。

这里app.use(bodyParser.json());默认作为

传递(req, res, next)

bodyParser.json() returns return function bodyParser (req, res, next) { .. }

所以它变成 --> app.use(function bodyParser (req, res, next) { .. });

但在您的情况下,您正在自己创建一个中间件,并且您负责将参数传递给 bodyParser,以便它可以访问所需的参数。

app.use((req, res, next) => {
    if (req.originalUrl === '/hooks') {
        next();
    } else {
        bodyParser.json()(req, res, next);
    }
});

查看下面app.use 的工作原理

https://github.com/expressjs/express/blob/master/lib/application.js#L187-L242