I wrote some simple Angular code to make a GET request to several API's but it's not always working. For instance when i make a request to
https://api.ofx.com/PublicSite.ApiService/OFX/spotrate/Individual/EUR/USD/10000?format=json
my code works perfectly.
But when using the same code and making a request to
the code is not working. Upon inspecting the response i see the following error message:
"SyntaxError: JSON.parse: unexpected end of data at line 1".
Now after doing some searching i came across the use of JSONP. So i then changed my code to use $http.jsonp… while also adding the "&callback=JSON_CALLBACK". I then checked my response (in the browser with firebug) and it received the JSON data successfully. However my Angularcode still throws me an error and it doesn't retrieve the response data for me.
(Also when I visit the URL in my browser I always get the JSON data).
I'm quite new to angularJS and just happened to stumble upon the JSONP method yesterday. From what i have read i guess the server is not returning the expected format (it returns normal JSON without the callbackname) and therefor my code is throwing an error? Maybe the server is not using/allowing JSONP at all? But why do i seem to get the correct response then and not when using a normal GET request?
My code:
var frankComparesApp = angular.module('frankComparesApp', []);
frankComparesApp.controller('frankComparesCtrl', function($scope, $http) {
$http.get('currency.json').then(function successCallback(response) {
$scope.currencyOptions = response.data;
$scope.choice = null;
}, function errorCall (response) {
// Function for handling failure.
$scope.currencyOptions=[];
}); // End of http.get
$scope.startComparing = function() {
$scope.ofxURL = 'https://www.fcexchange.com/umbraco/api/CurrencyExchangeRateApi/GetRate?callback=JSON_CALLBACK&from=EUR&to=GBP';
$http.jsonp($scope.ofxURL).then(function successCallback(response) {
$scope.answer = response.data;
}, function errorCall (response) {
$scope.answer = "fail";
}); // End of http.get
}; // End of startComparing();
}); // End of frankComparesCtrl