2015-10-03 38 views
0

由于我的跨域错误,我试图将我的$ http调用转换为JSONP调用。

请求的 资源上没有“Access-Control-Allow-Origin”标头。因此,'http://localhost:5000'因此不允许 访问。

我是一个初学者,已经提取从我的控制器我得到服务,我与发现那个地方努力改变$ HTTP到基于角文档上$ http.jsonp(URL)

这里是我的service.js

.service('NCAAF',function($http, $ionicLoading) { 
    return { 
    get: function() { 
     $ionicLoading.show({ 
     template: 'Loading...', 
     delay: 300 
     }) 
     return $http (
     { 
     method: 'GET', 
     cache: true, 
     crossDomain: true, 
     dataType: 'jsonp', 
     url: 'https://www.kimonolabs.com/api/[key]?callback=JSON_CALLBACK', 
     headers: { 
       'authorization': 'Bearer [auth]' 
     } 
     }); 
    } 
    }; 
}) 

controller.js

.controller('NCAAFCtrl', function ($scope, NCAAF, $ionicPopup, $ionicLoading) { 
    var doGet = function() { 

    NCAAF.get(). 
     success(function (data) { 
     $scope.data = data['results']['collection1']; 
     $ionicLoading.hide(); 
     }). 
     error(function() { 
     $ionicLoading.hide(); 
     var alertPopup = $ionicPopup.alert({ 
      title: 'Something went wrong', 
      template: 'Try reloading in a few seconds.' 
     }); 
     alertPopup.then(function() { 
      console.log('Fix this ish'); 
     }); 
     }). 
     finally(function() { 
     $scope.$broadcast('scroll.refreshComplete'); 
     }); 
    }; 
    $scope.doRefresh = function() { 
    doGet(); 
    }; 

    doGet(); 
}) 

回答

0

JSONP可以让你做cors请求,但这并不意味着你将能够得到正确的回应。

JSONP要求您将JSON响应封装到Javascript函数调用中。 当您执行JSONP请求时,查询字符串将设置一个名为 'callback'的参数,该参数将告诉您的服务器如何包装JSON响应。

服务器应该使用请求字符串中的回调参数来相应地设置 响应。

所以反应应该是

callback([ {“access_token”: “asdfsd”, “expires”: “86400" ,"type" : "bearer"} 
]); 

在角度它看起来像

angular.callbacks._0([ {“access_token”: “asdfsd”, “expires”: “86400" ,“type” : 
“bearer”} ]); 

但只为您的如何使JSONP呼叫信息,更改代码

return $http (
     { 
     method: 'GET', 
     cache: true, 
     crossDomain: true, 
     dataType: 'jsonp', 
     url: 'https://www.kimonolabs.com/api/[key]?callback=JSON_CALLBACK', 
     headers: { 
       'authorization': 'Bearer [auth]' 
     } 
     }); 

return $http.jsonp('https://www.kimonolabs.com/api/[key]?callback=JSON_CALLBACK',{ 
headers: { 
       'authorization': 'Bearer [auth]' 
     } 
});