使用Angular JS调用restful API时的跨域问题

Sye*_*yed 6 angularjs

我正在尝试访问一个安静的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");
    });
}
Run Code Online (Sandbox Code Playgroud)

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

Nix*_*Nix 5

更好的方法(小提琴示例)是使用$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'
    }
});
Run Code Online (Sandbox Code Playgroud)

注意JSON_CALLBACK我添加的查询字符串参数.在幕后角度使用它来为你设置回调.没有它它会破裂.


Ani*_*pta 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')
});
Run Code Online (Sandbox Code Playgroud)