我已经创建了一些带有一些逻辑的标准中间件,并且根据逻辑我需要调用一些第三方中间件。
使用app.use()添加中间件,这是我添加自定义中间件的地方。
进入我的中间件后,我无法访问app.use(),如何调用中间件?
以下是一些代码:
有什么想法吗?
const customerData = (req, res, next) => {
try {
console.log('Started');
if (process.env.STORE_CUSTOMER_DATA === 'true') {
// Here is some custom middleware that doesn't belong to me
//
// Returns a function (I confirmed it) ready to be called with res,req, next
//
let externalMiddlware = logger({
custom:true
});
// Do I return it ? Call it ? Trying everything and nothing seems to work
externalMiddlware(req,res,next); // ???
} else {
// DO not call external middleware, will break out of if and then call next()
}
console.log('Finished');
next();
} catch (err) {
next(err);
}
};
module.exports = customerData;
答案 0 :(得分:2)
我认为这应该可行但是如果你将回调委托给其他的externalMiddlware你不应该在customerData中调用next()使用这个第三中间件
所以你试试
const customerData = (req, res, next) => {
try {
console.log('Started');
if (process.env.STORE_CUSTOMER_DATA === 'true') {
let externalMiddlware = logger({
custom:true
});
return externalMiddlware(req,res,next);
} else {
return next(); // <= next moved
}
} catch (err) {
next(err);
}
};
module.exports = customerData;