Calling a middleware from within a middleware in NodeJS/ExpressJS

梦想与她 提交于 2021-02-08 11:00:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!