XMLHttprequest not working the twitch.tv api

1.5k views Asked by At

So I've been trying to access the twitch.tv api but every time i go to make a request i keep on getting the error:

 "XMLHttpRequest cannot load https://api.twitch.tv/kraken/streams/normalice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access."

I'm currently using the live-server package during the development process other wise I'm just using html, css, javascript. Here is my javascript:

var req = new XMLHttpRequest();
var url = 'https://api.twitch.tv/kraken/streams/normalice';

req.open("GET", url, true);
req.send();

req.onreadystatechange = function () {
   if (req.status == 200 && req.readState == 4){
      // do stuff here
      console.log('hurray it worked');
   }else{
      console.log(req.statusText);
      console.log(req.responseText);
   }
}

Does anyone have any ideas as to why am I encountering this error?

1

There are 1 answers

2
Cymen On BEST ANSWER

The Twitch.tv API doesn't support CORS. You need to use JSON-P (aka JSONP) to work around it. Read more about that in the Twitch.tv API docs. There is a prior answer on how to make a JSONP request with native JavaScript that may be useful.