Juan Pablo Pola Demoro
Juan Pablo Pola Demoro

Reputation: 153

AngularJS: consume web service from Wikipedia API

I'm developing an AngularJS app, and I want to display some info from Wikipedia, but I can't access the data in Angular, because the CORS restriction.

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

It make the call and I see it in firebug, I copied the url and paste it in another tab and I can see the JSON response.

In firebug also I'm seeing that I have to activate CORS but I don't know how to do it, and I tried a lot of solutions that I have been reading in StackOverflow and another sites.

Anyone can help me?

Thanks

Upvotes: 2

Views: 2018

Answers (1)

AWolf
AWolf

Reputation: 8980

You could use JSONP to avoid the CORS problem.

In short: The server have to support JSONP because it will create a return string with your callback as a wrapper around the returned JSON. Then your callback function will get the JSON as parameter. You don't need to manage that because Angular will handle this for you.

You'll only have to add &callback=JSON_CALLBACK to your url and use $http.jsonp.

Please have a look at the demo below and here at jsfiddle.

(There is a return from wikipedia but I don't know if the return is what you want.)

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>

Upvotes: 12

Related Questions