2015-10-20 91 views
-1

我目前正在嘗試學習如何在流星中執行HTTP請求。當我運行代碼時,我可以正確地在控制檯中查看數據。但是,在客戶端,我所得到的是「未定義」。我相信我正在同步運行HTTP.get方法。流星HTTP.call未定義在客戶端,在服務器端工作

.js文件

if (Meteor.isClient) { 
    Template.test.helpers({ 

     testGET: function(){ 
      var origin = Meteor.call('fetchFromService'); 
      console.log(origin); //-- Displays 'Undefined' 
     } 

    }); 
} 

if (Meteor.isServer) { 
    Meteor.methods({ 
     fetchFromService: function() { 
      this.unblock(); 
      var url = "https://httpbin.org/get"; 
      var result; 

      try{ 
       result = HTTP.get(url); 
      } catch(e) { 
       result = "false"; 
      } 

      console.log(result.data.origin); //-- Displays the data properly 
      return result.data.origin; 
     } 
    }); 
} 
+0

閱讀: [https://www.discovermeteor.com/blog/understanding-sync-async-javascript-node/](https://www.discovermeteor.com/blog/understanding-sync-async- javascript-node /) 然後,在Meteor文檔中: [http://docs.meteor.com/#/full/meteor_call](http://docs.meteor.com/#/full/meteor_call) 在客戶端上,如果您未傳遞迴調並且您不在存根中,則調用將返回** undefined **,您將無法獲取方法的返回值。這是因爲客戶端沒有光纖,所以實際上沒有任何方法可以阻止遠程執行方法 –

回答

0

這是異步,你有一個回調傳遞給call功能:

var origin = Meteor.call('fetchFromService', function(err, data) { 
    console.log(data); 
}); 

如果不通過回調,originundefined,直到請求結束。

+0

謝謝。我還發現了一篇文章,對我的理解進行了更好的解釋。 [https://www.discovermeteor.com/blog/understanding-sync-async-javascript-node/](https://www.discovermeteor.com/blog/understanding-sync-async-javascript-node/) –

相關問題