【问题标题】:How to optimize an Express.js route?如何优化 Express.js 路由?
【发布时间】:2011-10-26 14:14:47
【问题描述】:

我正在开发一个保留区域,其中包含以下几页:

/dashboard
/dashboard/profile
/dashboard/user
/dashboard/view

这是一个简单的用户控制面板。目前我有四个路线:

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

我想对其进行优化,因为在上述每条路线中,我都必须在开始时调用此函数:

authorized(req, function(auth){
   if (!auth) return next(errors.fire(403));
   /* route code */
});

这个函数检查用户是否登录,所以我需要在每个保留页面上调用它。

我会这样做:

app.all('/dashboard/*', function(req, res, next) { 

    authorized(req, function(auth){
       if (!auth) return next(errors.fire(403));           
       res.render(something, {})     
    });

});

res.render 调用中的something 必须是我需要打开的视图(页面)。

我想将其称为 ONE 次,以删除冗余代码。

这可能是面板的主页(如果用户想要 /dashboard)或页面(如果用户想要 /dashboard 内的页面,如 /dashboard/profile)在最后一种情况下我需要呈现“配置文件”视图.

(在将视图传递给 render() 之前,我必须进行检查,因为如果有人尝试 /dashboard/blablablabla,这应该是个问题。)

谢谢

【问题讨论】:

    标签: node.js routes express


    【解决方案1】:

    不是吗:

    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, {})     
        });
    });
    

    【讨论】:

      【解决方案2】:

      您可以将该函数作为路由中间件传递给每个路由,请查看http://expressjs.com/guide.html#route-middleware 了解更多信息。想法是这样的:

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

      然后在每条路线中:

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

      或者如果你的逻辑依赖于每个路由的某个角色,你可以像这样制作路由中间件:

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

      然后马上调用:

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

      【讨论】:

        猜你喜欢
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 2017-09-02
        • 2016-06-07
        • 1970-01-01
        • 2016-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多