How to optimize an Express.js route?

别说谁变了你拦得住时间么 提交于 2019-12-04 11:22:11

You can pass that function to each route as a route middleware, check http://expressjs.com/guide.html#route-middleware for more info. The idea would be this:

function mustBeAuthorized(req, res, next){
  /* Your code needed to authorize a user */
}

And then in each route:

app.all('/dashboard', mustBeAuthorized, function(req, res, next) { /* Code */ }); 

Or if your logic depends on a certain role for each route, you can make the route middleware like this:

function mustBeAuthorizedFor(role){
  return function(req, res, next){
     /* Your code needed to authorize a user with that ROLE */
  };
}

And then call it right away:

app.all('/dashboard', mustBeAuthorizedFor('dashboard'), function(req, res, next) { /* Code */ }); 

Isn't it:

app.get('/dashboard/:page?', function(req, res, next){
    var page = req.params.page;
    if ( ! page) {
      page = "dash-index"
    }

    authorized(req, function(auth){
       if (!auth) return next(errors.fire(403));           
       res.render(page, {})     
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!