Unable to read JSON in AngularJS $http from URL on local server

1.3k views Asked by At

I'm working on my first AngularJS app, and for my data I'm trying to read from a page in Drupal website on my local machine. It's running on Apache, and it's accessible from an alias URL (i.e. http://mylocalsite instead of http://localhost/mylocalsite). The page displays nothing but a JSON array of data, but for some reason, my Angular app is unable to read it using $http, either

angular.module('nbd7AppApp')
  .controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('http://mylocalsite/blogs/json'})
      .success(function(data) {
        $scope.nodes = data;
    });
  }]);

or

angular.module('nbd7AppApp')
  .controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http({method: 'GET', url: 'http://mylocalsite/blogs/json'})
      .success(function(data) {
        $scope.nodes = data;
    });
  }]);

However, if I put the JSON into a local file and access it like so

angular.module('nbd7AppApp')
  .controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('views/blogs.json')
      .success(function(data) {
        $scope.nodes = data;
    });
  }]);

it works perfectly. Is there something I need to do differently to be able to read it from the site URL?

Thanks.

1

There are 1 answers

0
wonder95 On BEST ANSWER

As indicated by my comment above, the answer was CORS. Once I added this line to my Apache virtual host:

Header set Access-Control-Allow-Origin "*"

the error went away.