ℙℕℤℝ 2017-07-01 17:18
浏览 148

Javascript读取文件

I have to read JSON file dynamically when I get "$ref" in Json schema.

I have tried accessing json file using node.js 'fs' module. But that gives error 'fs.readFile()' is not function.

I have later tried the Ajax call but I got following error.

XMLHttpRequest cannot load file:///Users/as6/Downloads/1099K.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Below is my code to read json file in javascript.

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}
readTextFile("file:///Users/as6/Downloads/1099K.json", function(text){
      var data = JSON.parse(text);
      console.log(data);
  });

How will I be able to read JSON file in javascript without Jquery?

  • 写回答

2条回答

  • weixin_33709364 2017-07-01 17:32
    关注

    The error is already telling you what's wrong. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

    The thing is you are trying to open a local file via the file:// protocol and as the browser is telling you, you can't XHR using that. The easy fix here would be to install a minimal static file server on your computer.

    Some more information about CORs here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

    As you mentioned nodejs, I will go ahead and assume you have it installed. I suggest https://www.npmjs.com/package/http-server so you can get up and running.

    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记