当前位置: 首页 > 知识库问答 >
问题:

CORS策略已阻止从“null”访问“http://github/..file.json”的XMLHttpRequest:

尉迟鸿熙
2023-03-14
function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send();
}

let button = document.createElement('button');
button.addEventListener("click", function () {
  // this requests the file and executes a callback with the parsed result once it is available
  fetchJSONFile('https://github.com/.../file.json', function(data){
      // do something with your data
      console.log(data);
  });
});
button.appendChild(document.createTextNode('JSON parse'));
document.body.appendChild(button); // append in body html
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script src="index.js" charset="utf-8"></script>
  </body>
</html>

我在没有本地服务器(apache等)的浏览器中打开index.html,然后单击按钮,它返回以下警告

CORS策略阻止了从源“null”访问“https://github.com/.../file.json”得XMLHttpRequest:请求得资源上没有“access-control-allow-origin”标头.

index.js:12跨源读取阻塞(CORB)阻塞的跨源响应https://github.com/.../file.json,具有MIME类型text/html。详见https://www.cromestatus.com/feature/5629709824032768。

通常情况下(在我的工作流程中),我创建了对同一个本地服务器的ajax请求,我混淆了一些这个概念,比如CORS(不知道)

共有1个答案

艾浩广
2023-03-14

编辑:

问题似乎在于您试图请求的资源不是原始的json,而是github页面。正在更改url

摘自https://github.com/.../hero.json

function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send();
}
fetchJSONFile("https://api.github.com/users/github",console.log)
 类似资料: