三生石@ 2018-01-03 18:58 采纳率: 100%
浏览 61

无法获取json数据

I want to get json data from API, but it seems not working. I think code will talk by itself

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

This code gives console Error 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.

I have suspicious that it might be CORS, but I have no idea how to fix it.

</div>
  • 写回答

1条回答 默认 最新

  • larry*wei 2018-01-03 20:02
    关注

    You could use: https://cors-anywhere.herokuapp.com/ service, by prepending your URL:

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

    You must consider that it is a free service that may not be 100% available.

    This API enables cross-origin requests to anywhere.

    Something like this:

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

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用