简体   繁体   中英

How can I define express middleware for all routes

I am trying to define one global middleware which will work for all routes of my app. I tried some ways but still got some issues.

var _gMDLW = function (req, res, next) {
  if(req.route) console.log('Called route ', req.route.path);
  next();
}

// Working fine and result on _gMDLW is /route1
app.get('/route1', _gMDLW, function (req, res, next) { return res.sendStatus(200); })


var globalRouter = new express.Router()

// Working fine and result on _gMDLW is /view
globalRouter.route('/view')
  .get(_gMDLW, function (req, res, next) { return res.sendStatus(200);})
app.use(globalRouter);

But problem is here

// Error in _gMDLW and getting /list instead of /items/list
var itemRouter = new express.Router()
itemRouter.route('/list')
  .get(_gMDLW, function (req, res, next) { return res.sendStatus(200);})
app.use('/items', itemRouter)

Second Question is is there any way to define/add _gMDLW inside app instead of adding in each route something like app.use(_gMDLW) ?

Thank you

You can use app.all() to resolve this issue

Example

app.all('*', _gMDLW);

function _gMDLW(req, res, next) {
    if (req.path == '/') return next();// redirect to homepage for guest

    next();//authenticated user
}

You can modify it as your requirement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM