【问题标题】:Session is not defined within Meteor.methods on server side but is on client side [duplicate]会话未在服务器端的 Meteor.methods 中定义,但在客户端[重复]
【发布时间】:2015-09-23 06:59:52
【问题描述】:

我有一个设置会话变量的方法:

Meteor.methods({
    updateSomething: (k) => {
        CollectionOfSomething.insert({
            k: k
        });
        Session.set('latestSomething', CollectionOfSomething.findOne({
            k: k
        });
    }
});

接下来发生的事情对我来说是矛盾的。由于这些方法是在lib 文件夹中定义的(这是一种正确的做法),因此调用会在客户端和服务器上调用该方法。在客户端,它为会话变量latestSomething 生成新值,并且每次都会刷新。但是在服务器上,我遇到了一个异常:

Exception while invoking method 'updateSomething' ReferenceError: Session is not defined

此异常只是一个警告,不会终止应用实例。但这似乎不是一个好习惯,所有这些消息都在服务器日志中填充,没有任何价值。

那我该怎么办? Meteor 的惯用方式是什么?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您不能在服务器上使用会话。它用于客户端的反应性。像这样在回调上设置它:

    Meteor.call('updateSomething', yourThing, function (err, id) {
      if (!err) {
        Session.set('somevar', id);
      }
    })
    

    你的流星方法看起来像这样

    Meteor.methods({
      updateSomething: function (thing) {
        return MyCollection.insert(thing);  // returns the id
      }
    });
    

    【讨论】:

      【解决方案2】:

      Session 对象仅在客户端上可用(请参阅http://docs.meteor.com/#/basic/session - 两个函数定义框都显示为“客户端”)。您最好的选择是return 获取您的CollectionOfSomething.findOne() 的结果,然后在客户端的回调函数中使用Session.set

      Session 是一个临时对象,在硬页面刷新或用户手动导航到其他页面时会丢失,因此在服务器上维护它没有任何意义。

      【讨论】:

      • “Session 是一个短暂的对象,当页面重新加载或路由更改时会丢失”Session 的全部目的完全不是
      • @Kyll,您可以链接到该声明的来源吗?像github.com/okgrow/meteor-persistent-session 这样的包之所以存在,是因为 Session 变量只存在于当前页面的生命周期中,因此命名为“Session”。
      • Session 是一个命名的全局 ReactiveDict,它被构建为在热重载和路由更改时持续存在。你的陈述充其量是非常不精确的。
      • 再一次,你有那个来源吗?我熟悉的流星不是那样工作的。见stackoverflow.com/questions/19617803/…Session 的目的不是持久性,而是内置的反应性。
      • @IsaacLyman, Session 将在硬页面引用上丢失,但它们会比当前路由和热代码推送持续更长时间。不这样做会很奇怪,因此它们基于纯ReactiveDict
      猜你喜欢
      • 2022-01-02
      • 2011-10-03
      • 2014-09-16
      • 2015-03-20
      • 2023-03-14
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多