2013-11-25 40 views
0

工作,我有一個像下面的代碼:HTTP.call GET方法不能在客戶端

var url = "http://www.telize.com/geoip"; 
HTTP.call("GET", url, function(err, res){ 
    if (err){ 
    console.log("HTTP call GET error: "+err); 
    } else { 
     var respJson = JSON.parse(res.content); 
     console.log("HTTP call GET response: "+JSON.stringify(respJson)); 
    }; 
}); 

我在服務器和客戶端運行該代碼。 在服務器上有確定的,我有JSON格式的信息響應。 在客戶端我有一個錯誤:「錯誤:網絡」。

如何在客戶端獲取JSON響應? 什麼錯了?

問候, DP

回答

1

你的問題是same-origin policy:你不能這樣做跨域AJAX請求的客戶端由於安全方面的原因。

有手頭有幾種解決方案:

  • 使用它運行在自己的域名代理。
  • JSONP
2

首先,客戶端代碼是受Same Origin Policy (SOP)。這就是爲什麼你不能做XHR跨域,除非遠程服務器實際上支持Cross-Origin Resource Sharing (CORS)

在傳統設置上,您可以使用JSONP或服務器作爲代理來解決此問題。

在流星,你可以創建a method on the server,做適合你的要求。這樣,它就是代表客戶端代碼執行請求的服務器。流星HTTP methods可以同步調用,所以你可以做一個return

//On the server 
Meteor.methods({ 
    'remoteGet' : function(url,options){ 
    return HTTP.get(url,options); 
    } 
}); 

//On the client 
Meteor.call('remoteGet','http://remoteurl.com/',{ 
    //...options... 
},function(error,response){ 
    //if an error happened, error argument contains the details 
    //if the request succeeded, the response will contain the response of the server request 
}) 
0

你只需要包裝在Meter.methods你的邏輯。 (見流星文件)。這是製作客戶端到服務器通話的「流星」方式。