Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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.

share|improve this question
    
Are there any error messages in the console? – Steven Lacks Jun 28 at 4:18
    
If you show the Chrome debugger on the page for your angular app, does the body of the http request that you see in the network tab look identical to what's in the local JSON file? Also is the character encoding set to UTF8 on the server that you're getting the JSON from? – Jason D Jun 28 at 4:19
    
Is the blogs/json part of the alias? I mean, does translate it to blogs.json? – Eric Martinez Jun 28 at 4:19
    
Oh, yeah, the console. Yes it gives me an this error: XMLHttpRequest cannot load mylocalsite/blogs/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:9000'; is therefore not allowed access. I'm running the angular app on a separate port from the one the site is on. – wonder95 Jun 28 at 4:27
    
you can add a white list for cross site access in angular. By default javascript can only access same domain for security purposes – Icycool Jun 28 at 4:36

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.