如何通过流星应用程序中的铁路由器限制访问?
How do limiting access through a iron-router in meteor app?
我有像这样锁定的路由文件:
Router.map(function(){
this.route('gameSmall', {path: '/'});
this.route('gameMedium', {path: '/game-medium'});
this.route('gameLarge', {path: '/game-large'});
});
等等
如果我想限制对某些路径的访问(仅限某些有密码的用户),我可以在路由器文件中配置吗?还是只能通过模板中的原生 js?
Iron Router 不支持通过配置文件限制访问。相反,您在 js 源代码中定义访问权限。
您可以限制全局和每条路线对路线的访问。两者都使用 onBeforeAction
事件来评估对路由的访问。
onBeforeAction
接受您编写访问规则的回调函数。
全局 onBeforeAction
事件可能如下所示:
Router.onBeforeAction(function() {
if (!Meteor.isServer) {
// Check the user. Whether logged in, but you could check user's roles as well.
if (!Meteor.userId()) {
this.render('pageNotFound'); // Current route cancelled -> render another page
} else {
this.next(); // Continue with the route -> will render the requested page
}
}
},
{
except: ['gameSmall']
});
注意第二个参数中的 except
字段。它包含一组要从 onBeforeAction 中排除的路由,因此始终呈现这些路由。还有一个字段 only
做相反的事情,包括要由 onBeforeAction 评估的路由。
另请注意,我使用了模板 pageNotFound(404 页面)。您可以像这样在 IR 的配置中定义该页面:
Router.configure({
notFoundTemplate: 'pageNotFound'
});
我有像这样锁定的路由文件:
Router.map(function(){
this.route('gameSmall', {path: '/'});
this.route('gameMedium', {path: '/game-medium'});
this.route('gameLarge', {path: '/game-large'});
});
等等
如果我想限制对某些路径的访问(仅限某些有密码的用户),我可以在路由器文件中配置吗?还是只能通过模板中的原生 js?
Iron Router 不支持通过配置文件限制访问。相反,您在 js 源代码中定义访问权限。
您可以限制全局和每条路线对路线的访问。两者都使用 onBeforeAction
事件来评估对路由的访问。
onBeforeAction
接受您编写访问规则的回调函数。
全局 onBeforeAction
事件可能如下所示:
Router.onBeforeAction(function() {
if (!Meteor.isServer) {
// Check the user. Whether logged in, but you could check user's roles as well.
if (!Meteor.userId()) {
this.render('pageNotFound'); // Current route cancelled -> render another page
} else {
this.next(); // Continue with the route -> will render the requested page
}
}
},
{
except: ['gameSmall']
});
注意第二个参数中的 except
字段。它包含一组要从 onBeforeAction 中排除的路由,因此始终呈现这些路由。还有一个字段 only
做相反的事情,包括要由 onBeforeAction 评估的路由。
另请注意,我使用了模板 pageNotFound(404 页面)。您可以像这样在 IR 的配置中定义该页面:
Router.configure({
notFoundTemplate: 'pageNotFound'
});