2017-10-18 25 views
0

我一直在嘗試從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

回答

0

您正在運行到同一起源的政策,並在瀏覽器使用CORS安全地訪問GitHub的提示。但是您無法訪問GitHubs服務器來進行更改。

GitHub不是API,因此不實現CORS頭。解決方法是使用代理服務,如RawGit來訪問您的文件。

相關問題