Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS in AngularJs

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

like image 403
ankitr Avatar asked Oct 05 '22 16:10

ankitr


People also ask

How do I add CORS in AngularJs 7?

Since, your angular app is running on 4200 port and backend running on 3000 port, the origin of both the application is different. To solve this problem, you can setup "nginx" in your machine. This will make all your requests from angular and backend, go via "nginx" server. Thus, solving the problem of CORS.

Why do we get CORS error in AngularJs?

CORS error due to browser's same origin policy. To get around this, you need to tell your browser to enable your client and your server to share resources while being of different origins. In other words, you need to enable cross-origin resource sharing or CORS in your application.


1 Answers

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.

like image 203
Quentin Avatar answered Oct 07 '22 06:10

Quentin