为流星铁路由器中的主要路线做一些不同的事情

Doing something different for main route in meteor iron router

我在我的 meteor 应用程序中使用 Iron-Route 进行路由。由于我有多个模块并且我想避免多次编码,所以我将用于身份验证(角色)的过滤器放在核心包中:

核心包

var filters = {
    authenticate: function () {
        var user;
        if (Meteor.loggingIn()) {
            this.layout('login');
            this.render('loading');
        } else {
            user = Meteor.user();
            if (!user) {
                this.layout('login');
                this.render('signin');
                return;
            }
            this.layout('StandardLayout');
            this.next();
        }
    }
}
Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    before: filters.authenticate
});
Router.route('/', function () {
    this.render('contentTemplate', { to: 'content' });
    this.render('navigationTemplate', { to: 'navigation' },)
});

其他套餐

...只需要这个:

Router.route('/article/:_id', {
    name: 'article',
    yieldTemplates: {
        'navigationPage':   { to: 'navigation' },
        'contentPage':      { to: 'content' } 
    }
});

现在在显示任何内容之前都会检查每个模块(路由)。 但我需要首页例外。主页 Route.route('/') 也应该被未登录的用户访问。我该怎么做?

您可以使用 iron:router 中的 onBeforeAction 挂钩,如下所示。 此解决方案假定您的登录路由名为 'login' 。但可以修改以满足您的需要。

./client/lib/hoooks/router.js

Router.onBeforeAction(function () {
    // all properties available in the route function
    // are also available here such as this.params
    if  (!Meteor.userId()) {
        //code for action to be taken when user is not logged in
        this.redirect('login');
        this.stop();
    } else {
        this.next();
    }
},{except: ['homeRouteName'] });

注意:将 'homeRouteName' 替换为您在 '/'

的路线名称