AngularJS cross-domain requests using $http service

坚强是说给别人听的谎言 提交于 2019-12-10 10:16:57

问题


I'm trying to learn AngularJS by making a simple web app using the Twitch API (https://github.com/justintv/Twitch-API) but I'm having trouble performing a GET request since it's a cross-domain request. This is what I have tried

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
        }
      })
    };
  }]);

but I get this for an error:

XMLHttpRequest cannot load https://api.twitch.tv/kraken. The request was redirected to 'http://www.twitch.tv/kraken', which is disallowed for cross-origin requests that require preflight.

I know I need to be using a JSONP request but how do I set headers that way? Can anyone show me an example of a JSONP request and how to set headers for it like I did in the example above? If I can't set headers in JSONP requests, how else do I set request headers?


回答1:


Make the request with:

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

This will return to you json and you wont have problems with XMLHttpRequest



来源:https://stackoverflow.com/questions/30229026/angularjs-cross-domain-requests-using-http-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!