所以我一直在尝试访问twitch.tv api,但是每次我去发出请求时,我都会不断收到错误消息:

 "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."


我目前在开发过程中使用的是live-server软件包,否则我只是使用html,css,javascript。这是我的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);
   }
}


是否有人对我为什么会遇到此错误有任何想法?

最佳答案

Twitch.tv API不支持CORS。您需要使用JSON-P(又名JSONP)来解决它。在the Twitch.tv API docs中了解有关此内容的更多信息。有一个prior answer on how to make a JSONP request with native JavaScript可能有用。

09-30 13:29
查看更多