【问题标题】:Failed to get json data获取json数据失败
【发布时间】:2018-01-03 18:58:37
【问题描述】:

我想从 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,但我不知道如何修复它。

【问题讨论】:

    标签: javascript json ajax


    【解决方案1】:

    您可以使用:https://cors-anywhere.herokuapp.com/ 服务,方法是在 URL 前添加:

    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);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2011-04-27
      • 2013-11-30
      相关资源
      最近更新 更多