【问题标题】:Reading JSON from a URL in AngularJS using $http.get使用 $http.get 从 AngularJS 中的 URL 读取 JSON
【发布时间】:2016-03-30 04:35:24
【问题描述】:

我为我正在开发的应用程序编写了一个 Flask 后端。简而言之,当调用 http://localhost:5000/allsongs/ 时,它会返回类似(或非常相似)以下内容:

[["King And Lionheart", "Of Monsters And Men", "My Head Is An Animal", "mp3"], ["Just One Yesterday", "Fall Out Boy", "Save Rock And Roll", "mp3"], ["Laughter Lines", "Bastille", "All This Bad Blood", "mp3"]]

我正在尝试使用 AngularJS 编写一个网络应用程序,该应用程序从该 URL 读取数据并使用 ng-repeat 来创建一个我可以搜索的列表。到目前为止,我已经写了这个:

<!DOCTYPE html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<html ng-app="myApp">

<body>

<script>
    angular.module('myApp', [])
        .controller('Songs', function Songs($scope, $http) {
    $http.get('http://localhost:5000/allmusic').then(function(response) {
      $scope.songs = response;
    });
  }
    );
</script>

<input placeholder="Search..." type="text" ng-model="search" />


<div ng-controller="Songs">
<p>{{songs}}</p>
</div>
<p ng-repeat="song in songs | filter:search | orderBy:name">{{ song }}</p>
</body>
</html>

加载页面时显示的只是页面顶部的搜索字段。

另外,当我刷新页面时,我看到我的 Flask 服务器被调用,所以我知道 $http.get 正在工作。

任何建议都会很棒!

【问题讨论】:

  • 哎呀,ng-repeat 复制粘贴错了,原来是:&lt;div ng-controller="Songs"&gt;&lt;p ng-repeat="song in songs | filter:search | orderBy:name"&gt;{{ song }}&lt;/p&gt;&lt;/div&gt;
  • 你不应该使用 $scope.songs = JSON.parse(response)
  • 您是否对 then 函数内的 $http.get 响应执行了 console.log 以验证您是否获得了预期的数据?
  • @Ludo - 如果响应已经是来自服务器的 json 格式,则不需要解析响应。它将在 Angular 中直接可用和分配。
  • @DanielNalbach - 我为响应添加了一个 console.log,但我发现了这个:XMLHttpRequest cannot load http://localhost:5000/allmusic. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.,在删除 console.log 时它仍然存在。简单来说,日志什么也没做,但是那个错误就在那里。

标签: javascript python html angularjs json


【解决方案1】:

当您不在服务器端呈现 HTML 时,这可能是一个 CORS 问题。所以你有两个选择。

  1. 添加一些返回 index.html 的路由器以及您需要的所有 Angular 代码。
  2. 添加一些标头响应更改。

遗憾的是,我没有使用 Flask 的经验,但在 Node.js 中,第二个解决方案可能看起来像这样

app.use((req,res)=>{
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    req.next();
  });

【讨论】:

  • 终于!我修好了它!你是对的,这是一个 CORS 问题。我用 JavaScript 弄了一会儿,但无济于事。相反,我使用了我发现的名为 flask-cors 的东西。它基本上为您添加了正确的标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 2013-05-10
相关资源
最近更新 更多