Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross domain issue in calling a restful API using Angular JS

Tags:

angularjs

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/

like image 404
Syed Avatar asked Jan 16 '14 05:01

Syed


2 Answers

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.

like image 89
Nix Avatar answered Oct 22 '22 00:10

Nix


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')
});
like image 1
Anil Gupta Avatar answered Oct 22 '22 01:10

Anil Gupta