【发布时间】:2020-09-10 11:48:24
【问题描述】:
我是 javascript 的新学生。我一直在练习从 localhost 加载 JSON 到本地 html 文件,但不断看到 CORS 错误。
[问题]:Chrome / Firefox 上的不同 CORS 错误消息
- Chrome:“访问 XMLHttpRequest 在 'file:/// ...(本地路径)... charStat.json' 从源 'null' 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。"
- Firefox:“跨域请求被阻止:同源策略不允许读取 file:/// ...(本地路径)... charStat.json 处的远程资源。(原因:CORS 请求不http)。”
[我试过的]
- 使用 php + nginx 设置一个简单的 Web 服务器。没有域,只有 localhost (http://127.0.0.1)
- 在 localhost (http://127.0.0.1/charStat.json) 下找到 JSON 文件
- 在 Firefox about:config 中,选择退出“privacy.file_unique_origin”(设置为“false”)
battle.html(本地文件)
<!DOCTYPE html>
<html lang="en-US">
<!-- abbreviated -->
<body>
<div id = "charNow">
<table id= "chardata" border="2">
<thead>
<th>Class</th>
<th>CT</th>
<th>Level</th>
<th>HP</th>
<th>EN</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script src="js/battle.js"></script>
<script src="js/jquery-3.5.1.js"></script>
</html>
battle.js(本地文件)
// abbreviated
const request = new XMLHttpRequest();
const path = 'http://127.0.0.1/charStat.json';
const statTable = function () {
$.getJSON(`charStat.json`, function(data) {
$.each(data.statsByClass, function(i, f) {
let tblRow = "<tr>"
+ "<td>" + f.class + "</td>"
+ "<td>" + f.ct + "</td>"
+ "<td>" + f.statTable[1].level + "</td>"
+ "<td>" + f.statTable[1].hp + "</td>"
+ "<td>" + f.statTable[1].en + "</td>"
+ "</tr>"
$(tblRow).appendTo("#chardata tbody");
});
});
}
function loadJSONFile(file, callback) {
request.open(`GET`, file, true);
request.responseType = 'json';
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == `200`) {
callback(request.response);
}
}
request.send(null);
}
loadJSONFile(path, statTable);
charStat.json(在本地主机下)
{
"statsByClass" : [
{
"class" : "Warrior",
"ct" : 300,
"statTable" : [
{ "level" : 0, "hp" : 1000, "en" : 200, "str" : 20, "vit" : 16, "agl" : 10, "spd" : 15, "int" : 8, "xpToNextLv" : 1 },
{ "level" : 1, "hp" : 1200, "en" : 300, "str" : 24, "vit" : 20, "agl" : 12, "spd" : 19, "int" : 9, "xpToNextLv" : 300 },
{ "level" : 2, "hp" : 1400, "en" : 300, "str" : 26, "vit" : 22, "agl" : 13, "spd" : 19, "int" : 9, "xpToNextLv" : 400 },
// ... abbreviated ...
]
}
]}
【问题讨论】:
标签: javascript json cors