6

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/

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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')
});

2 Comments

There are two pieces to this method:JSONP and the callback you added to the end of the URL string. Please explain these details and I will give you +1.
@Nix JSONP is used for making cross domain request & callback is JSONP format in which sever should wrap the response data with callback method e.g if u send url param callback=my_result then on server side you need to generate response with wrapping callback value as function e.g my_result({"id", 1 });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.