How to enable CORS in AngularJs

ankitr picture ankitr · May 23, 2014 · Viewed 395.1k times · Source

I have created a demo using JavaScript for Flickr photo search API. Now I am converting it to the AngularJs. I have searched on internet and found below configuration.

Configuration:

myApp.config(function($httpProvider) {
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

Service:

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.flickrPhotoSearch = function() {
        return $http({
            method: 'GET',
            url: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=3f807259749363aaa29c76012fa93945&tags=india&format=json&callback=?',
            dataType: 'jsonp',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});

Controller:

myApp.controller('flickrController', function($scope, dataService) {
        $scope.data = null;
        dataService.flickrPhotoSearch().then(function(dataResponse) {
            $scope.data = dataResponse;
            console.log($scope.data);
        });
    });

But still I got the same error. Here are some links I tried:

XMLHttpRequest cannot load URL. Origin not allowed by Access-Control-Allow-Origin

http://goo.gl/JuS5B1

Answer

Quentin picture Quentin · May 23, 2014

You don't. The server you are making the request to has to implement CORS to grant JavaScript from your website access. Your JavaScript can't grant itself permission to access another website.