无法获取json数据

时间:2018-01-03 18:58:37

标签: javascript json ajax

我想从API获取json数据,但似乎无效。我认为代码会自行说话



var URL = 'https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en';

getData(URL);

function getData(source){
    xhr = new XMLHttpRequest();
        
    xhr.onload = function(){
        if(xhr.status === 200){
            data = JSON.parse(xhr.responseText);
            console.log(data);
          
            
        }
    }

    xhr.open('GET', source, true);
    xhr.send(null);
}




此代码提供控制台错误Failed to load https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我怀疑它可能是CORS,但我不知道如何修复它。

1 个答案:

答案 0 :(得分:-1)

您可以使用:https://cors-anywhere.herokuapp.com/服务,前缀您的网址:

https://cors-anywhere.herokuapp.com/ https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en

您必须考虑这是免费服务,可能不是100%可用。

  

此API可以向任何地方启用跨源请求。

这样的事情:



var URL = 'https://cors-anywhere.herokuapp.com/https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en';

getData(URL);

function getData(source) {
  xhr = new XMLHttpRequest();
  xhr.onload = function() {
    if (xhr.status === 200) {
      data = xhr.responseText;
      console.log(data);
    }
  }
  xhr.open('GET', source, true);
  xhr.send(null);
}