26
//Create an Angular Module.
var newsModule = angular.module('NewsModule', []);

//Create an Angular Controller.
newsModule.controller('newsCtrl', ['$scope', '$http', function ($scope, $http) {
//function retrives POST,UPDATE,DELETE,GET data

$http.defaults.headers.put = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
        };
        $http.defaults.useXDomain = true;

    $scope.throughdata = function (){

 delete $http.defaults.headers.common['X-Requested-With'];
         $http.get('http://www.google.com').then(function(data,error){
            alert(data);
            alert(error);
            $scope.days=data.data;
          });



    }
}
 ]);

But I have getting following errors

XMLHttpRequest cannot load http://www.google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Shankar Kamble
  • 2,983
  • 6
  • 24
  • 40
  • 1
    Just wondering why you're not using [`ngResource`](https://docs.angularjs.org/api/ngResource/service/$resource) for these types of tasks. It's meant to sit on top of `$http`, to make it easier to work with. – yurisich Jun 07 '14 at 13:16

1 Answers1

47

Access-Control-Allow-Origin is set on the response from server, not on client request to allow clients from different origins to have access to the response.

In your case, http://www.google.com/ does not allow your origin to have access to the response. Therefore you cannot read it.

For more information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • 2
    Anyone with a Rails backend, see http://stackoverflow.com/questions/17858178/allow-anything-through-cors-policy and https://github.com/cyu/rack-cors – Dennis Hackethal Dec 27 '14 at 03:03