为什么不带参数调用此 Express 中间件?
Why is this Express middleware not being called with arguments?
我正在开发一个需要 bodyParser
到 运行 的中间件,但我不想让应用程序将其作为依赖项引入。相反,我想制作一个需要它的包并导出这样的中间件:
//routes.js
app.use('/', middlewareWrapper(thing));
//middlware.js
export function middlewareWrapper(thing) {
return function addBody(req, res, next) {
function othermiddleware(_req, _res) {
// do something with thing and _req
return next();
}
return bodyParser.json()(req, res, othermiddleware);
};
}
这看起来可行,并且调用了 othermiddleware
,但没有参数。
我找到了另一个答案,基本上以相同的方式解决了这个问题(它很旧,但 JS 仍然以相同的方式工作):
为什么 othermiddleware
被调用时没有参数?
因为你
next();
没有传递参数。通常快递是这样的:
bodyParser.json()(
req,
res,
() => {
othermiddleware(req,res,next);
}
);
或者你使用一些绑定魔法:
bodyParser.json()(req, res, othermiddleware.bind(this,req,res,next));
问题是 bodyParser.json()
返回的中间件只是像这样调用 next()
(即没有参数)。在这里,您将 othermiddleware
作为 bodyParser.json()
返回的中间件的旁边传递。因此它不包含任何参数。
此外,bodyParser 不会更改 req/res
对象的原始引用。所以主 req/res
对象仍然引用同一个对象。所以你不需要传递参数。您也可以在 othermiddleware
函数中简单地使用相同的 req/res
对象。
return function addBody(req, res, next) {
function othermiddleware() {
// You should be able to use req and res modified by bodyParser.
// You dont need arguments to be passed.
return next();
}
return bodyParser.json()(req, res, othermiddleware);
};
我正在开发一个需要 bodyParser
到 运行 的中间件,但我不想让应用程序将其作为依赖项引入。相反,我想制作一个需要它的包并导出这样的中间件:
//routes.js
app.use('/', middlewareWrapper(thing));
//middlware.js
export function middlewareWrapper(thing) {
return function addBody(req, res, next) {
function othermiddleware(_req, _res) {
// do something with thing and _req
return next();
}
return bodyParser.json()(req, res, othermiddleware);
};
}
这看起来可行,并且调用了 othermiddleware
,但没有参数。
我找到了另一个答案,基本上以相同的方式解决了这个问题(它很旧,但 JS 仍然以相同的方式工作):
为什么 othermiddleware
被调用时没有参数?
因为你
next();
没有传递参数。通常快递是这样的:
bodyParser.json()(
req,
res,
() => {
othermiddleware(req,res,next);
}
);
或者你使用一些绑定魔法:
bodyParser.json()(req, res, othermiddleware.bind(this,req,res,next));
问题是 bodyParser.json()
返回的中间件只是像这样调用 next()
(即没有参数)。在这里,您将 othermiddleware
作为 bodyParser.json()
返回的中间件的旁边传递。因此它不包含任何参数。
此外,bodyParser 不会更改 req/res
对象的原始引用。所以主 req/res
对象仍然引用同一个对象。所以你不需要传递参数。您也可以在 othermiddleware
函数中简单地使用相同的 req/res
对象。
return function addBody(req, res, next) {
function othermiddleware() {
// You should be able to use req and res modified by bodyParser.
// You dont need arguments to be passed.
return next();
}
return bodyParser.json()(req, res, othermiddleware);
};