【问题标题】:Getting a SyntaxError when trying to fetch JSON data from local files [duplicate]尝试从本地文件中获取 JSON 数据时出现 SyntaxError [重复]
【发布时间】:2020-03-02 05:08:48
【问题描述】:

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

“JSON.parse:第 1 行第 1 列的数据意外结束”。

我已经为 fetch 函数尝试了许多参数,但始终出现至少 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
    }
  ]
}

我想控制台记录数据以确保其正常运行。

【问题讨论】:

  • 获取数据时可能出错。您能否检查一下 chrome 开发工具的网络选项卡,调用返回的内容。
  • 你发布的JSON是有效的,所以在实际应用中肯定有不同的地方。
  • 正如 Nicolas 所说,我会假设响应的第 1 行类似于换行符之类的东西,而实际的 JSON 数据从第 2 行开始。
  • Chrome 是这么说的
  • app.js:20 Fetch API 无法加载 file:///C:/data.json。不支持 URL 方案“文件”。 getData @ app.js:20 app.js:20 Uncaught (in promise) TypeError: Failed to fetch at HTMLButtonElement.getData (app.js:20)

标签: javascript json fetch


【解决方案1】:

如果您使用 fetch 检索未运行服务器的本地文件,即通过file:/// 协议而不是@ 987654324@或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' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

原因还是限制您访问文件的协议和跨源问题。

所以即使你的文件来自同一个主机(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 访问的静态文件提供服务

【讨论】:

    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2015-04-26
    • 2018-02-17
    • 2018-05-13
    • 2022-09-24
    相关资源
    最近更新 更多