AngularJS cross-domain requests using $http service

Isaac Perez picture Isaac Perez · May 14, 2015 · Viewed 14.5k times · Source

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?

Answer

Иван Иванов picture Иван Иванов · May 28, 2015

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