I'm trying to access a restful API. This gives error. How to overcome this Cross domain issue?
The error is '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");
});
}
This is my fiddle http://jsfiddle.net/U3pVM/2654/
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'
}
});
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.
Use JSONP for escape Cross Domain
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')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With