大佬教程收集整理的这篇文章主要介绍了node.js – 如何优化Express.js路由?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
/dashboard /dashboard/profile /dashboard/user /dashboard/view
app.all('/dashboard',function(req,res,next) { /* Code */ }); app.all('/dashboard/profile',next) { /* Code */ }); app.all('/dashboard/user',next) { /* Code */ }); app.all('/dashboard/view',next) { /* Code */ });
我想优化它,因为在上面的每一条路线中我都必须在开头调用这个函数:
authorized(req,function(auth){ if (!auth) return next(errors.fire(403)); /* route code */ });
此函数检查用户是否已记录,因此我需要在每个保留页面上调用它.
我会做的事情如下:
app.all('/dashboard/*',next) { authorized(req,function(auth){ if (!auth) return next(errors.fire(403)); res.render(something,{}) }); });
res.render调用中的内容必须是我需要打开的视图(页面).
这可能是面板的主页(如果用户需要/仪表板)或页面(如果用户想要一个页面/仪表板如/ dashboard / profilE),在最后一种情况下我需要渲染“profile”视图.
(我必须在将视图传递给render()之前进行检查,因为如果有人尝试/ dashboard / blablablabla它应该是一个问题.)
谢谢
function mustBeAuthorized(req,next){ /* Your code needed to authorize a user */ }
然后在每条路线:
app.all('/dashboard',mustBeAuthorized,next) { /* Code */ });
或者,如果您的逻辑依赖于每个路由的某个角色,您可以像这样制作路由中间件:
function mustBeAuthorizedFor(rolE){ return function(req,next){ /* Your code needed to authorize a user with that ROLE */ }; }
然后立即打电话:
app.all('/dashboard',mustBeAuthorizedFor('dashboard'),next) { /* Code */ });
以上是大佬教程为你收集整理的node.js – 如何优化Express.js路由?全部内容,希望文章能够帮你解决node.js – 如何优化Express.js路由?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。