我试图访问一个宁静的API。这使错误。如何克服这种跨域问题?
I'm trying to access a restful API. This gives error. How to overcome this Cross domain issue?
错误是访问控制允许来源标头的请求的资源present
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/
一个更好的办法来做到这一点(小提琴例如)是使用 $ http.jsonp
。
A better way to do this (fiddle example) is to use $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
查询字符串参数。幕后角度使用该设置的回调为您服务。没有它,它会打破。
Notice the JSON_CALLBACK
query string parameter I added. Behind the scenes angular uses that to setup its callbacks for you. Without it it will break.