由于所请求的资源中没有“Access-Control-Allow-Origin”,导致无法加载JSON文件

问题描述:

我一直在尝试从Github Repo中的JSON文件获取数据。我只使用XMLHttpRequest()由于所请求的资源中没有“Access-Control-Allow-Origin”,导致无法加载JSON文件

$(function() { 
    load(); 
    function load() { 
     var fetch = new XMLHttpRequest(); 

     fetch.open(
      "GET", 
      "https://github.com/prvnbist/Periodic-Elements-App-Using-JSON-And-JQuery/blob/master/elements.json", 
      true 
    ); 

    fetch.onload = function() { 
     if (this.status == 200) { 
      var elem = JSON.parse(this.responseText);` 
     } 
    } 
    } 
}); 

这是我得到的错误!

Failed to load https://github.com/prvnbist/Periodic-Elements-App-Using-JSON-And-JQuery/blob/master/elements.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access.

代码工作完全在本地主机上着,当然但codepen它给我这个错误是合法出于安全目的,但我一直没能得到解决它。

这里的链接到Codepen - https://codepen.io/prvnbist/pen/EwOapM

+1

不要直接点击github。使用https://rawgit.com/ – Taplar

您正在运行到同一起源的政策,并在浏览器使用CORS安全地访问GitHub的提示。但是您无法访问GitHubs服务器来进行更改。

GitHub不是API,因此不实现CORS头。解决方法是使用代理服务,如RawGit来访问您的文件。