Cors error in AngularJS

1

I have a question that I have been trying to find a solution for, but nevertheless it has not been entirely clear to me, I have an application made in AngularJS that consumes a JSON from an external source , the detail is the following I'm using the service $resource to make the get however I get error cors:

However when I use Jquery with the functions $.ajax or $.getJSON I do not get a Cors error? Why is this behavior?

I leave the screenshots of the code:

Request with ajax of Jquery gives 200 :

My question is: with the functions of ajax and getJSON of Jquery does not generate error of Cors and with the service $resource yes?

    
asked by RaKKoS_NeT 06.01.2017 в 06:12
source

1 answer

2

Instead of using $resource , you should use $http .

  

$resource : It is a "factory" that creates a resource object which allows to interact with data sources RESTful server side.

     

$http : It is a service that facilitates communication with remote servers HTTP via XMLHttpRequest or < a href="https://en.wikipedia.org/wiki/JSONP"> JSONP .

The endpoint https://s3.amazonaws.com/dolartoday/data.json is not a API REST , it is simply a JSON file, so it does not support the OPTIONS method.

Try to do it like this:

(function(angular) {
  'use strict';
  
  angular.module('httpExample', [])
  .controller('FetchController', ['$scope', '$http', '$templateCache',
    function($scope, $http, $templateCache) {
      $scope.method = 'GET';
      $scope.url = 'https://s3.amazonaws.com/dolartoday/data.json';

      $scope.fetch = function() {
        $scope.code = null;
        $scope.response = null;

        $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
          then(function(response) {
            $scope.status = response.status;
            $scope.data = response.data;
          }, function(response) {
            $scope.data = response.data || 'Request failed';
            $scope.status = response.status;
        });
      };
    }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="httpExample">
  <div ng-controller="FetchController">
    <input type="text" ng-model="url" />
    <button id="fetchbtn" ng-click="fetch()">fetch</button><br/>
    <pre>http status code: {{status}}</pre>
    <pre>http response data: {{data}}</pre>
  </div>
</div>
    
answered by 06.01.2017 / 15:23
source