AngularJS获取请求失败

时间:2016-05-04 13:24:26

标签: angularjs json get jsonp

我写了一些简单的Angular代码来向几个API提出GET请求,但它并不总是有效。例如,当我向

提出请求时
  

https://api.ofx.com/PublicSite.ApiService/OFX/spotrate/Individual/EUR/USD/10000?format=json

我的代码完美无缺。

但是当使用相同的代码并向

发出请求时
  

https://www.fcexchange.com/umbraco/api/CurrencyExchangeRateApi/GetRate?callback=JSON_CALLBACK&from=EUR&to=GBP

代码无效。检查响应后,我看到以下错误消息:

  

"语法错误:JSON.parse:第1行"意外的数据结尾。

现在经过一些搜索后,我发现了JSONP的使用。所以我然后改变我的代码使用$ http.jsonp ... 同时还添加"& callback = JSON_CALLBACK"。然后我检查了我的响应(在浏览器中使用了firebug)并成功收到了JSON数据。但是我的Angularcode仍然会给我一个错误,它也没有为我检索响应数据。

(当我在浏览器中访问URL时,我总是得到JSON数据)。

我对angularJS很陌生,昨天恰巧偶然发现了JSONP方法。 根据我的阅读,我猜服务器没有返回预期的格式(它返回没有callbackname的普通JSON),因此我的代码抛出错误?也许服务器根本不使用/允许JSONP?但是为什么我似乎得到了正确的响应,而不是在使用正常的GET请求时?

我的代码:

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

1 个答案:

答案 0 :(得分:0)

这看起来像CORS问题。您尝试从不同于www.fcexchange.com的域请求数据,因此您收到的错误就像我在plunkr中所做的那样

在devtools中检查您的控制台。

相关问题