返回流星呼叫方法

Returning meteor call method

本文关键字:方法 呼叫 流星 返回      更新时间:2023-11-26

我今天第一次使用Meteor:)

我制作了一个简单的表单,它向Ruby API发出POST请求,以返回auth_code

Meteor.call("serverEx", emailInput, passwordInput)运行良好,在Meteor服务器中显示成功返回。

所以我的问题是,我试图将auth_code返回到流星客户端中的一个变量中

console.log(finalVar)不工作,显示未定义。

有什么想法吗?有一种感觉,我错过了一些非常基本的东西。

if (Meteor.isClient) {
  Template.templateLogin.events({
    'submit form': function(event) {
      var emailInput = event.target.email.value;
      var passwordInput = event.target.password.value;
      var finalVar = Meteor.call("serverEx", emailInput, passwordInput);
      console.log(finalVar);
      return false;
    }
  });
}
if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
  /////////////////////
  // METHODS
  /////////////////////
  Meteor.methods({
    "serverEx" : function(a, b) {
       var httpMethod = "POST";
       var httpUrl = "http://xxxxxxx.herokuapp.com/signin";
       HTTP.call(httpMethod, httpUrl, {'content-type': 'application/json; charset=utf-8', params: {
         email: a,
         password: b
       }}, function (error, result) {
         if (result.statusCode === 200) {
             console.log("Success, the authcode is " + result.data.auth_token);
             return result.data.auth_token;
         }
         if (result.statusCode === 401) {
           console.log("Login failed, invalided email or password");
         }
      });
    }
  });
}

也许可以尝试使用回调选项。

 var finalVar;
     Meteor.call("serverEx", emailInput, passwordInput,function(err,result){
         if(!err){
              finalVar = result;
          }
      });      
          console.log(finalVar);

我认为您遇到的问题是同步。通常,我会使用Meteor.call回调函数进行这样的方法调用:

Meteor.call("serverEx", emailInput, passwordInput, function(error, result){
    if (error)
       alert(error.reason)
    else
       finalVar = result;
});

此外,看起来您没有从服务器端方法返回任何内容。试试这个。

"serverEx" : function(a, b) {
   var httpMethod = "POST";
   var httpUrl = "http://xxxxxxx.herokuapp.com/signin";
   var httpResult;

   HTTP.call(httpMethod, httpUrl, {'content-type': 'application/json; charset=utf-8', params: {
     email: a,
     password: b
   }}, function (error, result) {
     if (result.statusCode === 200) {
         console.log("Success, the authcode is " + result.data.auth_token);
         httpResult = result.data.auth_token;
     }
     if (result.statusCode === 401) {
       console.log("Login failed, invalided email or password");
     }
  });
  return httpResult;
}