问题
I have created some standard middleware with some logic, and depending on the logic I need to call some 3rd party middleware.
Middleware is added using app.use(), which is where I add my custom middleware.
Once in my middleware I no longer have access to app.use(), how do I call the middleware?
Here is some code:
Any ideas ?
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;
回答1:
I think this should work but if you delegate the callback to this other externalMiddlware you should not call next() in customerData use this 3rd middleware
so have you try
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;
来源:https://stackoverflow.com/questions/47572752/calling-a-middleware-from-within-a-middleware-in-nodejs-expressjs