【问题标题】:Loading JSON from localhost using XMLHttpRequest keeps generating CORS error [duplicate]使用 XMLHttpRequest 从本地主机加载 JSON 不断产生 CORS 错误 [重复]
【发布时间】: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


    【解决方案1】:

    将json文件(charStat.json)复制到battle.html(和battle.js)所在的同一目录。

    启动本地服务器 -> 然后你可以通过ajax调用加载json:

    fetch('charStat.json')
      .then(response => response.json())
      .then(data => console.log(data));
    

    【讨论】:

    • 谢谢@Marc。我将fetch 代码添加到我的 js 文件中,它可以工作。幸运的是,不需要移动 charStat.json 文件,而是使用了我定义的 path 并且仍然有效。
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2016-02-04
    • 2018-08-01
    • 2019-06-30
    • 2018-09-06
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    相关资源
    最近更新 更多