【问题标题】:How do I know if a method was called server-side or client-side (from the server)?我如何知道一个方法被称为服务器端还是客户端(来自服务器)?
【发布时间】:2015-08-16 10:44:08
【问题描述】:

在我的 Meteor 应用程序中,我在服务器上定义了一个方法,如下所示:

/* global Meteor */
Meteor.methods({
    notifyRequestRejected: function (username, reason) {
        if (!Meteor.userId()) {
            throw new Meteor.Error(403, 'Access denied');
        }
        return Meteor.http.post('…');
    }
});

由于我只希望经过身份验证的用户和我的服务器端(受信任)代码能够调用该方法,我如何检查该方法是在服务器端调用还是在客户端调用?有类似this.calledFromServer 的方法吗?

【问题讨论】:

  • 反对者,需要解释一下吗?

标签: meteor


【解决方案1】:

可以通过检查this.connection 属性来检查方法调用是在服务器端还是客户端。

如果不为null,则表示该方法是从客户端调用的。

因此,要确保调用者是经过身份验证的用户或某些服务器端代码,请使用:

Meteor.methods({
    notifyRequestRejected: function (username, reason) {
        if (!Meteor.userId() && this.connection) {
            throw new Meteor.Error(403, 'Access denied');
        }
        // etc.
    }
});

【讨论】:

    【解决方案2】:

    您可以使用this.isSimulationMeteor.isClient 来检测客户端存根的执行。

    您可以否定这些表达式以检测服务器端环境或使用Meteor.isServer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 2015-11-04
      • 2018-06-06
      • 1970-01-01
      相关资源
      最近更新 更多