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)