简体   繁体   English

如何为所有路由定义快速中间件

[英]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) ? 第二个问题是,有什么方法可以在app内部定义/添加_gMDLW ,而不是在每个路由中添加诸如app.use(_gMDLW)类的东西吗?

Thank you 谢谢

You can use app.all() to resolve this issue 您可以使用app.all()解决此问题

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 您可以根据需要进行修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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