首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试从本地文件获取JSON数据时获取SyntaxError

尝试从本地文件获取JSON数据时获取SyntaxError
EN

Stack Overflow用户
提问于 2019-11-05 19:06:31
回答 1查看 642关注 0票数 0

尝试从本地文件中获取json数据并继续获取

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

对于fetch函数,我尝试了许多参数,但是我始终得到至少一个错误。

代码语言:javascript
运行
复制
    function getData() {
      fetch('./data.json', {mode: 'no-cors'})
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      })
    };

JSON数据

代码语言:javascript
运行
复制
{
  "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的数据,以确保它是否正常运行。

EN

回答 1

Stack Overflow用户

发布于 2019-11-05 19:56:01

如果您使用fetch检索没有运行服务器的本地文件,即通过Fetch API cannot load file:///C:/your/path/to/data.json. URL scheme "file" is not supported.协议访问JSON文件,而不是通过http://https://访问该文件,则始终会得到错误的file:///文件。

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

代码语言:javascript
运行
复制
// 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中创建快速服务器

通过在工作目录中键入npm install -g http-server

  • Change来安装http-server,其中yoursome.html lives

  • 通过发出http-server -c-1

启动http服务器。

这将运行一个Node.js httpd,它将目录中的文件作为可从http://localhost:8080访问的静态文件提供服务。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58717906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档