简体   繁体   中英

Access to XMLHttpRequest at 'http://github/..file.json' from origin 'null' has been blocked by CORS policy:

I am trying requesting a json file guesting in github (eg : http://github/..file.json ), I have a javascript code (without jquery) unlike this question that use it to request that file with an ajax.

index.js

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

index.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>

I open the index.html in the browser without a local server (apache, etc...), next i clicked the button it returns the following warning

Access to XMLHttpRequest at ' https://github.com/.../file.json ' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

index.js:12 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://github.com/.../file.json with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Normally (in my work flow) I created ajax request to same local server and i confuse a few this concepts like CORS (No idea)

EDIT:

Seems the issue was in the fact that you were trying to request resource that wasn't raw json but instead a github page. Changing url

from https://github.com/.../heroes.json

to https://raw.githubusercontent.com/.../heroes.json

is the solution.

ORIGINAL ANSWER: There is nothing wrong with your code, when i try to request some json file using your function i receive the correct response as prsented here:

 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) 

The issue seems to be with CORB

Cross-Origin Read Blocking (CORB) is an algorithm that can identify and block dubious cross-origin resource loads in web browsers before they reach the web page. CORB reduces the risk of leaking sensitive data by keeping it further from cross-origin web pages. In most browsers, it keeps such data out of untrusted script execution contexts. In browsers with Site Isolation, it can keep such data out of untrusted renderer processes entirely, helping even against side channel attacks like Spectre.

1) Cross-origin requests for images, media, and fonts will receive empty responses if the response from the network has an HTML, XML, or JSON content type and a nosniff response header. The responses' headers will be filtered to CORS safelisted response headers and CORS response headers.

Discussion: https://github.com/whatwg/fetch/pull/686

2) Cross-origin requests from media tags will receive empty responses if the response from the network has a 206 (range request) status and an HTML, XML, or JSON content type. The responses' headers will be filtered to CORS safelisted response headers and CORS response headers.

3) Cross-origin requests from script tags will receive empty responses if the response from the network has an HTML, XML, or JSON content type and is confirmed to be HTML, XML, or JSON using confirmation sniffing logic. The responses' headers will be filtered to CORS safelisted response headers and CORS response headers. Such responses would not have run successfully anyway, but now they will not generate a syntax error. (Note: responses with nosniff headers and the wrong content type are already blocked from script tags.)

4) Cross-origin requests from script tags will receive empty responses if the response from the network starts with a JSON security prefix and is not otherwise permitted via CORS. The responses' headers will be filtered to CORS safelisted response headers and CORS response headers. Such responses would not have run successfully anyway, but now they will not trigger infinite loops (eg, when the for(;;); prefix is present). (Note: these responses will be blocked in other cases as well, but the effect is not observable for other tag types, such as images.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM