如何优化 Express.js 路线?

2024-03-28

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

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

});

the somethingres.render 调用内部必须是我需要打开的视图(页面)。

我想称呼它ONE时间,删除多余的代码。

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

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

谢谢


您可以将该函数作为路由中间件传递给每个路由,检查http://expressjs.com/guide.html#route-middleware 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 */ }); 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何优化 Express.js 路线? 的相关文章

随机推荐