2014-01-16 41 views
6

我試圖訪問一個restful API。這給了錯誤。如何克服這個跨域問題?使用Angular JS調用restful API時出現跨域問題

的錯誤是'Access-Control-Allow-Origin' header is present on the requested resource

function Hello($scope, $http) { 

$http.get('http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=atf6ya6bbz3v5u5q8um82pev'). 
    success(function(data) { 
     alert("Success"); 
    }). 
    error(function(data){ 
     alert("Error"); 
    }); 
} 

這是我的小提琴http://jsfiddle.net/U3pVM/2654/

回答

1

使用JSONP逃生跨域

var request_url = 'http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=atf6ya6bbz3v5u5q8um82pev&callback=JSON_CALLBACK'; 

$http({ 
    method: 'JSONP', 
    url: request_url 
}).success(function(data, status , header, config){ 
     alert('Success') 
}) 
.error(function(data, status , header, config){ 
     alert('error') 
}); 
+0

該方法有兩個部分:JSONP和您添加到URL字符串末尾的回調。請解釋這些細節,我會給你+1。 – Nix

+0

@Nix JSONP用於製作跨域請求和回調是JSONP格式,其中sever應該用回調方法包裝響應數據,例如,如果你發送url param callback = my_result,那麼在服務器端你需要生成包裝回調值的響應爲函數例如my_result({「id」,1}); –

5

一個更好的辦法來做到這一點(fiddle example)是使用$http.jsonp

var url = 'http://api.worldweatheronline.com/free/v1/weather.ashx'; 
return $http.jsonp(url, { 
    params: { 
     callback: 'JSON_CALLBACK', 
     q: 'London', 
     format:'json', 
     num_of_days: 5, 
     key: 'atf6ya6bbz3v5u5q8um82pev' 
    } 
}); 

注意我添加的查詢字符串參數JSON_CALLBACK。幕後角色使用它來爲你設置回調。沒有它會破壞。