如何优化一个Express.js路线?

我正在开发一个具有以下几页的保留区域:

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

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

我会做这样的事情:

 app.all('/dashboard/*', function(req, res, next) { authorized(req, function(auth){ if (!auth) return next(errors.fire(403)); res.render(something, {}) }); }); 

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

我想调用它一次,删除多余的代码。

这可能是面板的主页(如果用户需要/仪表板)或页面(如果用户想要一个页面里面/仪表板像/仪表板/configuration文件)在最后一种情况下,我需要呈现“configuration文件”视图。

(我必须做一个检查前通过视图render(),因为如果有人尝试/仪表板/ blablablabla应该是一个问题。)

谢谢

您可以将该函数作为路由中间件传递给每个路由,请参阅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 */ }); 

或者,如果您的逻辑取决于每个路由的某个angular色,则可以使路由中间件如下所示:

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

是不是:

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