首先,你使用了
bind
错误(关于函数的编写方式):绑定的第一个参数是要用作
this
调用函数时;只有后续的参数定义了调用函数时的参数。所以你想要
cb0.bind(null, data)
而不是
cb0.bind(data)
.
但如果我使用
绑定
概念,然后如何传递其他必需的属性(
req
,
res
和
next
)?
(它们是参数,不是属性。)Express在调用函数时会执行此操作。这些参数将跟随您通过“烘焙”到函数中的参数
绑定
.您的功能已正确设置以处理该订单(
data
,
请求
,
物件
,
下一个
),所以有了变化,你应该准备好出发了。
所以:
app.get('/example/d', [cb0.bind(null, data), cb1.bind(null, data)], (req, res, next) => {
// ...
为了清楚起见,下面是一个函数示例,其中数据通过
绑定
被称为进一步的论点:
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) => {
// ...
两种方式都可以。