Reputation: 2607
I got a sample API online. I want to use it for my Angular sample app. But, I'm not able to access the below restful API. Please have a look at my code.
function Hello($scope, $http) {
$http({method: 'GET', url: 'http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'}).
success(function(data) {
alert("Success");
}).
error(function(data){
alert("Error");
});
}
Thank you
Nizam
Upvotes: 2
Views: 339
Reputation: 30416
You need to use JSONP in order to request data via Ajax across domains. The good news is you can just replace this code:
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");
$scope.greeting = data["content"];
console.log(data["content"]);
}).
error(function(data){
alert("Error");
});
}
With this code (demo):
function Hello($scope, $http) {
$http
.jsonp('http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=atf6ya6bbz3v5u5q8um82pev&callback=JSON_CALLBACK')
.success(function(data) {
alert("success");
$scope.greeting = data["content"];
console.log(data["content"]);
})
.error(function(data){
alert("Error");
});
}
Here is what it took, the $http.jsonp()
method requires the string 'callback=JSON_CALLBACK'
to appear somewhere in the URL. It will replace this with a generated function name that the .success()
will reference. This won't magically work with servers that don't support JSONP but in this case the server URL does.
Upvotes: 2