I am trying to create a service in AngularJS which would fetch me JSON data from a website. I wrapped the service in a factory method as shown below
App.factory('httpService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
return {
getData : function() {
var url = "http://www.reddit.com/.json?callback=JSON_CALLBACK";
return $http.jsonp(url).then(
function(result) {
return result;
});
}
}
});
The problem I'm coming across is that I receive an error Uncaught SyntaxError: Unexpected token :
. When I use get()
instead of json()
I get a 501
/CORS error.
The URLs from where I am trying to fetch the data are: http://api.4chan.org/b/1.json http://www.reddit.com/.json
following is a link to my jsfiddle with the rest of the code.
http://jsfiddle.net/fatgamer85/adPue/3/
Does any one has any idea on how to solve this?
EDIT: I have managed to get the data and solved the issue. Thanks to sza
Following is the code which I've used if anyone's interested
var myApp = angular.module("client", []);
myApp.factory('myXHRService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
return {
getData : function(url) {
return $http.jsonp(url).then(
function(result) {
return result.data;
}
);
}
}
});
myApp.controller('MainCtrl', function($scope, myXHRService) {
$scope.xhrData = {};
$scope.data = {};
$scope.url = "http://www.reddit.com/.json?jsonp=JSON_CALLBACK";
myXHRService.getData($scope.url).then(function(data) {
var xhrData = angular.fromJson(data);
$scope.xhrData = xhrData.data.children;
});
});
myApp.config(function($httpProvider){
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
The main difference here is the callback in URL parameters jsonp
apart from that, everything works fine and dandy.
I think it may relate to API endpoint issue of Reddit.com. If you try this API, it will work using jsonp
var url = "http://www.reddit.com/top.json?jsonp=JSON_CALLBACK";
For the API /.json
, I suggest you implement the server side code to retrieve data though it returns valid JSON but somehow can't be accessed correctly across domain.