javascript - AngularJS:使用来自维基百科 API 的 Web 服务

标签 javascript angularjs cors wikipedia-api

我正在开发一个 AngularJS 应用程序,我想显示来自维基百科的一些信息,但我无法访问 Angular 中的数据,因为 CORS 限制。

     $scope.wikipediaData =  $http.get('http://es.wikipedia.org/w/api.php?titles='+$scope.country.name.toLowerCase()+'&rawcontinue=true&action=query&format=json&prop=extracts');

它发出调用,我在 firebug 中看到它,我复制了 url 并将其粘贴到另一个选项卡中,我可以看到 JSON 响应。

在 Firebug 中,我也看到我必须激活 CORS,但我不知道该怎么做,我尝试了很多我在 StackOverflow 和其他网站上阅读过的解决方案。

谁能帮帮我?

谢谢

最佳答案

你可以使用 JSONP避免 CORS 问题。

简而言之:服务器必须支持 JSONP,因为它会创建一个带有回调的返回字符串作为返回 JSON 的包装器。然后你的回调函数将获取 JSON 作为参数。 您不需要管理它,因为 Angular 会为您处理。

您只需将 &callback=JSON_CALLBACK 添加到您的 url 并使用 $http.jsonp

请查看下面和此处的演示 jsfiddle .

(维基百科有返回,不知道是不是你想要的)

var app = angular.module('myApp', []);

app.factory('wikiService', function($http) {
      
    var wikiService = {
        get: function(country) {
            return $http.jsonp('http://es.wikipedia.org/w/api.php?titles=' + country.name.toLowerCase() + '&rawcontinue=true&action=query&format=json&prop=extracts&callback=JSON_CALLBACK');
        }
    };
    
    return wikiService;
});
    
app.controller('MainController', function($scope, wikiService) {

    wikiService.get({name: 'Germany'}).then(function(data) {
        console.log(data);
        $scope.wikiData = data.data;
    });
      
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainController">
    <pre ng-bind="wikiData | json"></pre>
</div>
</div>

关于javascript - AngularJS:使用来自维基百科 API 的 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29442008/

相关文章:

javascript - 如何在谷歌条形图中显示百分比?

javascript - 可以通过选项卡选择单选按钮吗?

angularjs - 如何在 ngTagsInput 中设置标签的颜色?

angular - 部署时没有 'Access-Control-Allow-Origin' 问题

javascript - CORS 错误 header 允许来源 * http 与 https

javascript - 我可以将 HTML 元素的文本绑定(bind)到字符串对象吗?

javascript - 为什么使用 `<button>` 作为 `&lt;input type="文件“>` not work, but ` <a>` 的委托(delegate)在 Safari 中有效?

javascript - Angular $interval 在超过 'count' 参数后是否会自行取消?

javascript - AngularJS : Understanding service when using $http. 帖子

node.js - 在 React 前端从 Zoho API 获取数据时出现 CORS 错误