Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at .....

Problem

When using $http.get I have a problem: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ..... This can be fixed by moving the resource to the same domain or enabling CORS

$http.get('...').success(function(data){
        console.log(status);
    }).error(function(data){
        //console.log(data)
    });
app.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
Problem courtesy of: Tam Vo

Solution

Cross-origin requests are requests made from one domain to a different one (in client side). They are by default prohibited in the Web for security reasons. So, if you have a webpage in http://www.yours.com making an AJAX request to http://www.other.com/get/resource, then this AJAX request will be rejected. This issue can be resolved in 3 ways :

  • Fetch the API (/get/resource) in http://www.yours.com so that the request is not a CORS request anymore.
  • Transform the architecture of your application, so that this request from http://www.yours.com is made in the backend (aka not in the form of AJAX) and then passed on your webpage.
  • Enable the server in http://www.other.com to allow CORS requests from http://www.yours.com. This can be done by adding the header Origin: http://www.yours.com in the responses of the server. Thus, it requires that you have access to the second server's configuration.

Additional Resources for CORS :

  1. HTML5 turorial
  2. W3 specification
Solution courtesy of: Dimos

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.