XMLHttprequest not working the twitch.tv api

冷暖自知 提交于 2019-12-24 15:49:45

问题


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:


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.



来源:https://stackoverflow.com/questions/30772644/xmlhttprequest-not-working-the-twitch-tv-api

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