express 路由器中间件中带有附加参数的函数数组

Array of functions with additional arguments in the express router middleware

const cb0 = function (data, req, res, next) {
  console.log('CB0')
  next()
}

const cb1 = function (data, req, res, next) {
  console.log('CB1')
  next()
}

app.get('/example/d', [cb0, cb1], (req, res, next) => {
  console.log('the response will be sent by the next function ...')
  next()
}, (req, res) => {
  res.send('Hello from D!')
})

从上面的代码中,我传递了一个函数数组 [cb0, cb1],每个函数都需要一些 any 类型的 data 属性和其他参数,例如 req , resnext.

早些时候,我尝试使用 bind 概念传递如下格式的数据属性。 app.get('/example/d', [cb0.bind(data), cb1.bind(data)], (req, res, next)

但是如果我使用bind概念,那么如何传递其他必需的属性(reqresnext)? 有没有其他方法可以传递所有参数,包括 data 而不绑定?或者我们在 express 中使用函数数组有什么限制吗?

首先,您错误地使用了 bind(关于您的函数的编写方式): bind 的第一个参数是调用函数时用作 this 的值;只有后续参数定义参数以在调用时提供函数。所以你想要 cb0.bind(null, data) 而不是 cb0.bind(data).

But if I use the bind concept, then how to pass the other required attributes (req, res and next)?

(它们是参数,不是属性。)Express 在调用您的函数时会这样做。这些参数将遵循您通过 bind“融入”您的函数的参数。您的功能已经正确设置以处理该订单(datareqresnext),因此随着更改,您应该可以开始了。

所以:

app.get('/example/d', [cb0.bind(null, data), cb1.bind(null, data)], (req, res, next) => {
    // ...

为清楚起见,下面是一个函数示例,其中数据通过 bind 绑定到它,并使用更多参数调用:

function example(data, other) {
    console.log(`data = ${JSON.stringify(data)}, other = ${JSON.stringify(other)}`);
}

const ex = example.bind(null, "baked in arg");

// Emulating Express calling the middleware:
ex("passed arg");


旁注:您不必将中间件函数放在数组中,express 很乐意将它们作为离散参数代替:

app.get('/example/d', cb0.bind(null, data), cb1.bind(null, data), (req, res, next) => {
    // ...

两种方式都可以。