XMLHttprequest无法处理twitch.tv api

时间:2015-06-11 05:52:10

标签: javascript api cors xmlhttprequest twitch

所以我一直在尝试访问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);
   }
}

有没有人对我遇到此错误的原因有任何想法?

1 个答案:

答案 0 :(得分:2)

Twitch.tv API不支持CORS。您需要使用JSON-P(也称为JSONP)来解决它。在the Twitch.tv API docs中详细了解相关内容。有prior answer on how to make a JSONP request with native JavaScript可能有用。