ℙℕℤℝ 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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)