Cross-domain issue when calling untrusted API using Angular JS

I am trying to access the updated API. This gives an error. How to overcome this cross domain problem?

Error '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/

+6
source share
2 answers

The best way to do this ( example script ) 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' } }); 

Note the JSON_CALLBACK query string parameter that I added. Behind the scenes, angular uses this to set up its callbacks for you. Without it, it will break.

+5
source

Use JSONP to 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') }); 
+1
source

All Articles