Javascript 通过'访问XMLHttpRequest;http://github/..file.json' 来自原点';空';已被CORS策略阻止:
我尝试在github中请求json文件guesting(例如:),我有一个javascript代码(没有jquery),与使用ajax请求该文件不同 index.jsJavascript 通过'访问XMLHttpRequest;http://github/..file.json' 来自原点';空';已被CORS策略阻止:,javascript,html,json,ajax,Javascript,Html,Json,Ajax,我尝试在github中请求json文件guesting(例如:),我有一个javascript代码(没有jquery),与使用ajax请求该文件不同 index.js function fetchJSONFile(path, callback) { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (httpRequest.readySt
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
我在没有本地服务器(apache等)的浏览器中打开index.html,然后单击按钮返回以下警告
访问位于的XMLHttpRequest
''
来源“null”已被CORS策略阻止:否
“Access Control Allow Origin”标头出现在请求的服务器上
资源
js:12跨源读取阻塞(CORB)阻塞跨源
响应
使用MIME类型text/html。看见
更多
细节
通常(在我的工作流程中)我创建了对同一本地服务器的ajax请求,我混淆了一些概念,如CORS(不知道)编辑:
问题似乎在于您试图请求的资源不是原始json,而是github页面。更改url
从
到
这就是解决办法
原始答案:
您的代码没有问题,当我尝试使用您的函数请求一些json文件时,我收到了正确的响应,如下所示:
函数fetchJSONFile(路径,回调){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange=函数(){
if(httpRequest.readyState==4){
if(httpRequest.status==200){
var data=JSON.parse(httpRequest.responseText);
if(回调)回调(数据);
}
}
};
httpRequest.open('GET',path);
httpRequest.send();
}
fetchJSONFile(“https://api.github.com/users/github“,console.log)是的,您请求的url与我不同,可以看到您请求的标题,
内容类型:application/json;charset=utf-8
与我的url不同,我的url是text/html
确切地说,这有没有办法更改这些标题?您不是请求原始json,而是请求github页面,请更改指向此页面的链接