使用$ http服务的AngularJS跨域请求

时间:2015-05-14 04:03:10

标签: angularjs rest http-headers jsonp cross-domain-policy

我正在尝试使用Twitch API(https://github.com/justintv/Twitch-API)创建一个简单的Web应用程序来学习AngularJS,但我在执行GET请求时遇到了问题,因为它是一个跨域请求。这就是我试过的

angular.module('streamPlaylisterAppServices', []).factory('twitchService', ['$http',
  function($http) {
    return function(usercode){
      console.log("usercode inside service is: " + usercode)
      var authHeader = 'OAuth' + usercode;

      return $http({
        method: 'GET',
        url: ' https://api.twitch.tv/kraken',
        cache: false,
        headers:{
          'Accept': 'application/vnd.twitchtv.v3+json',
          'Authorization': 'OAuth ' + usercode
        }
      })
    };
  }]);

但是我得到了一个错误:

  

XMLHttpRequest无法加载https://api.twitch.tv/kraken。请求   被重定向到'http://www.twitch.tv/kraken',这是不允许的   对于需要预检的跨源请求。

我知道我需要使用JSONP请求但是如何设置标头呢?任何人都可以向我展示一个JSONP请求的示例以及如何为它设置标头,就像我在上面的示例中所做的那样?如果我无法在JSONP请求中设置标头,我还应该如何设置请求标头?

1 个答案:

答案 0 :(得分:4)

请求:

$http.jsonp('https://api.twitch.tv/kraken/games/top?limit=' + number + '&callback=JSON_CALLBACK')

这将返回给你json,你不会遇到XMLHttpRequest

的问题
相关问题