簡體   English   中英

Meteor HTTP.call 在客戶端未定義,在服務器端工作

[英]Meteor HTTP.call undefined on Client-side, working on Server-side

我目前正在嘗試學習如何在 Meteor 中執行 HTTP 請求。 當我運行代碼時,我可以在控制台中正確地看到數據。 但是,在客戶端,我得到的只是“未定義”。 我相信我正在同步運行 HTTP.get 方法。

.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;
        }
    });
}

它是異步的,您必須將回調傳遞給call函數:

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

如果您不傳遞回調,則在請求完成之前, origin將是undefined的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM