javascript - 尝试从本地文件获取 JSON 数据时出现语法错误

标签 javascript json fetch

尝试从本地文件获取 json 数据并不断获取

"JSON.parse: unexpected end of data at line 1 column 1" .

我已经尝试了获取函数的许多参数,但我总是收到至少 1 个错误。

    function getData() {
      fetch('./data.json', {mode: 'no-cors'})
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      })
    };

JSON 数据

{
  "CustomerJohn": [
    {
      "month": "April",
      "transaction": 1,
      "price": 57
    },
    {
      "month": "April",
      "transaction": 2,
      "price": 89
    },
    {
      "month": "May",
      "transaction": 1,
      "price": 163
    },
    {
      "month": "May",
      "transaction": 2,
      "price": 43
    },
    {
      "month": "May",
      "transaction": 3,
      "price": 221
    },
    {
      "month": "June",
      "transaction": 1,
      "price": 99
    },
    {
      "month": "June",
      "transaction": 2,
      "price": 201
    }
  ]
}

我想对数据进行 console.log 以确保其正常运行。

最佳答案

您将始终收到错误Fetch API 无法加载 file:///C:/your/path/to/data.json。不支持 URL 方案“file”。如果您使用 fetch 检索未运行服务器的本地文件,即通过 file 访问 JSON 文件:/// 协议(protocol),而不是 http://https://

为了访问它,您必须处于某个服务器环境中并且可以使用 XMLHttpRequest 来检索数据。我在下面为您准备了工作代码:

// Method which actually read json using XMLHttpRequest and promise
const jsonFileReader = async path => {
    return new Promise((resolve, reject) => {

        const request = new XMLHttpRequest();
        request.open('GET', path, true);
        request.responseType = 'blob';

        request.onload = () => {
          const reader = new FileReader();

          reader.onload = e => resolve(e.target.result);
          reader.onerror = err => reject(err);
          reader.readAsDataURL(request.response);
        };

        request.send();
    });
}

// This mthod will return the JSON
const returnJsonData = async (url) => {
    const jsonData = await jsonFileReader(url);
    console.log('Here is your JSON data: => ', jsonData);
    return jsonData;
}

// Calling the function where you put URL
returnJsonData('./file.json');

此外,如果您不在服务器上运行此代码,您将收到以下错误,Access to XMLHttpRequest at 'file:///C:/your/path/to/data.json' from origin 'null' 已被 CORS 策略阻止:跨源请求仅支持以下协议(protocol)方案:http、data、chrome、chrome-extension、https。

原因还是协议(protocol)和跨源问题限制了您访问该文件。

因此,即使您的文件源自同一主机(localhost),但只要方案不同(http/file),它们就会被视为不同的来源。

<小时/>

如何在 Node.js 中创建快速服务器

  1. 通过输入 npm install -g http-server 安装 http-server
  2. 切换到 yoursome.html 所在的工作目录
  3. 通过发出http-server -c-1启动您的http服务器

这会运行 Node.js httpd,它将目录中的文件作为静态文件提供,可从 http://localhost:8080

访问

关于javascript - 尝试从本地文件获取 JSON 数据时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58717906/

相关文章:

javascript - 将基于文本的 div 放置在圆内的相对位置

IOS - 如何在 Core Data Swift 中将数据插入具有关系的不同表中

javascript - 隐藏元素直到加载完成(ng-cloak 不是我需要的)

javascript - 为什么我无法从我的 Json 文件中检索数据?

json - 如何在swift 5中从jsonserialization中的对象类型获取数据

json - 尝试解析 JSON 值时出错

swift - CollectionViewCell 不显示单元格或加载核心数据字符串

php - 使用获取的数据中的第二行或第三行(等)来确定变量

javascript - 分隔文本到嵌套 javascript 对象/JSON

javascript - 如何在 javascript 中转换数组/数据集?