【问题标题】:Assumption: Is it true that Meteor.call() tries to run in the client environment first?假设: Meteor.call() 是否首先尝试在客户端环境中运行?
【发布时间】:2013-12-22 04:44:41
【问题描述】:

由于this question而用Meteor做实验,得出以下结论:

在共享目录(客户端/服务器)中定义,这将引发引用错误

if(Meteor.isServer) {
    // could depend on server logic, this is not Meteor.isServer!
    serverVar = true;
}    

Meteor.methods({
    myMethod: function() {
        if(serverVar) {
            return "secret";
        } else {
            throw Error();
        }
    }
}

然后,在客户端:

Meteor.call("myMethod", function(err, res) {
    console.log(res);
}

导致:ReferenceError: serverVar

但是这段代码,只在服务器端定义,运行完美:

// could depend on server logic, this is not Meteor.isServer!
serverVar = true;

Meteor.methods({
    myMethod: function() {
        if(serverVar) {
            return "secret";
        } else {
            throw Error();
        }
    }
}

请注意,我只切换到服务器端目录而不是共享目录,并删除了 if 子句。

我认为这两种方法应该是等效的,忽略了代码可见的事实 仅受Meteor.isServer限制时在客户端上。

这使我得出这样的结论:Meteor 使用第一种方法时,会尝试在客户端上运行代码,而无需明确限制在服务器上。真的吗?!还有什么解释?

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    好的,我明白了。使用第一种方法,Meteor 会抛出一个ReferenceError。这是由于该功能的客户端模拟。此功能在文档here 中进行了描述。

    所以代码适用于这两种方法,但是当也在客户端上定义时,它会抛出 ReferenceError。将范围限制为服务器时,不再发生这种情况。

    【讨论】:

      【解决方案2】:

      不要使用 Meteor.isServer()

      Meteor.isServer 可用于限制代码运行的位置,但它不能 防止代码被发送到客户端。

      check this answer 构建您的流星应用程序

      【讨论】:

        【解决方案3】:

        我想你可能只需要一个 var serverVar;在最顶端(共享)

        【讨论】:

          猜你喜欢
          • 2014-10-16
          • 1970-01-01
          • 2021-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-23
          • 1970-01-01
          • 2013-11-29
          相关资源
          最近更新 更多