【问题标题】:Meteor.userId can only be invoked in method calls. (Meteor IronRouter)Meteor.userId 只能在方法调用中调用。 (流星铁路由器)
【发布时间】:2016-02-03 06:12:55
【问题描述】:

我正在为我的应用程序使用 IronRouter。最近想休息一下:

Router.route('/api/hello', { where: 'server' })
  .get(function () {
    this.response.end('Helo world');
});

我得到了这个例外:

Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions. at AccountsServer.userId (accounts_server.js:80:13) at AccountsServer.user (accounts_common.js:53:23) at Object.Meteor.user (accounts_common.js:230:19) at [object Object]. (lib/routes_permission.js:33:21) at packages/iron_router/lib/router.js:277:1 at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1) at [object Object].hookWithOptions (packages/iron_router/lib/router.js:276:1) at boundNext (packages/iron_middleware-stack/lib/middleware_stack.js:251:1) at runWithEnvironment (packages/meteor/dynamics_nodejs.js:110:1) at packages/meteor/dynamics_nodejs.js:123:1

我在 '(lib/routes_permission.js:33:21)' 中跟踪了这个问题,似乎一切都很好。

// user with no role
Router.onBeforeAction(function() {
  var user = Meteor.user(); //This is the line.
  if(user && !user.roles) {
    this.render('roles');
    return;
  }
  this.next();
});

我不知道为什么会出现这个异常。不过,我的出版物中没有任何 Meteor.userId()。

有什么见解吗?

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    服务器端路由像 REST 端点一样被访问,因此它们没有身份验证的概念(Meteor.userMeteor.userId 会抛出错误)。因为您的routes_permission.js 文件是在共享目录中定义的,所以它的规则也被用于服务器路由。你有一些关于如何解决这个问题的选择,但最简单的可能就是像这样用Meteor.isClient 包裹你的onBeforeAction

    if (Meteor.isClient) {
      Router.onBeforeAction(...);
    }
    

    【讨论】:

    • 正在考虑这个问题,但不确定是否有一种“更清洁”的方式来做到这一点,使用 { where: 'client' } ...
    猜你喜欢
    • 1970-01-01
    • 2015-08-11
    • 2014-09-03
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2014-09-07
    • 2015-01-29
    相关资源
    最近更新 更多