简体   繁体   中英

Getting JSON from URL in AngularJS?

I have a node.js server providing the AngularJS app on port 8000, and a Python server exposing data over HTTP as JSON on port 80.

Loading in my browser http://localhost:8000/app/List.html renders a blank page . Why?

Controllers.js

function FooListCtrl($scope, $http) {
    $http.get('localhost/foo/list').success(function (data) {
        $scope.foo_lists = data;
    });
}

FooListCtrl.$inject = ['$scope', '$http'];

List.html

<!doctype html>
<html lang="en" ng-app>
    <head>
        <meta charset="utf-8">
        <script src="lib/angular/angular.js"></script>
        <script src="js/controllers.js"></script>
    </head>
    <body ng-controller="FooListCtrl">
        <code>{{foo_lists | json}}</code>
    </body>
</html>

curl -X GET localhost/foo/list -i

HTTP/1.0 200 OK
Date: Wed, 15 May 2013 18:28:49 GMT
Server: WSGIServer/0.1 Python/2.7.4
Content-Length: 30
Content-Type: application/json

{"Foo": ["bar", "can", "haz"]}

The problem is most likely, as others have mentioned, a cross-origin issue. It's not only about using the same domain, but also the same port. To bypass this, you can either use JSONP , which is a very easy solution designed for this very purpose or use the Cross Site Request Forgery (XSRF) Protection , which uses cookie validation and other measures to ensure security while providing get and post functionality (this is not the easiest solution).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM