Meteor.user() 在路由器内部返回未定义



我在Meteor中有以下设置:

当用户点击根 URL 并且未登录时,我会显示一个欢迎页面。

当用户点击根URL并登录时,我想重定向到用户的"事物"页面。

问题是,Meteor.user()在路由器内部是未定义的。

构建

它的正确方法是什么?

<body>
    {{# if currentUser}}
        {{> thing}}
    {{else}}
        {{> welcome}}
    {{/if}}
</body>
var MyRouter = Backbone.Router.extend({
    routes: {
       "": "welcome",
       "/things/:thingId": "thing"
    },
    welcome: function() {
        var user = Meteor.user();
        console.log(user); //undefined
        // Redirect to user's thing
    },
    thing: function(thingId) {
        Session.set("currentThingId", thingId);
    }
});

您确定您当前的用户已经注册了吗?对Meteor.user()的调用在两端(客户端和服务器)都可用,因此您应该有权访问路由器文件中的当前用户实例。例如,我测试当前用户是否在我的路由器中登录,如下所示:

var requireLogin = function() { 
    if (! Meteor.user()) {
        if (Meteor.loggingIn())
            this.render(this.loadingTemplate);
        else
            this.render('accessDenied');
            this.stop();
        }
 }
Router.before(requireLogin, {only: 'postSubmit'})

在 mongo 数据库中的服务器端检查:

$ meteor mongo
$ >db.users.find().count() // Should be greather than 0

客户端控制。例如,打开 chrome 控制台,只需输入 :

Meteor.user();
null // Means user is currently not logged in 
     // otherwise you should receive a JSON object

最新更新