AngularJS cross-domain requests using $http service

14,533

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

Share:
14,533
Isaac Perez
Author by

Isaac Perez

Updated on June 06, 2022

Comments

  • Isaac Perez
    Isaac Perez almost 2 years

    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?