尝试从本地文件中获取JSON数据时出现SyntaxError

尝试从本地文件获取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","price": 163
    },"price": 43
    },"transaction": 3,"price": 221
    },{
      "month": "June","price": 99
    },"price": 201
    }
  ]
}

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

chkxchkx 回答:尝试从本地文件中获取JSON数据时出现SyntaxError

如果您使用访存来获取未运行服务器的本地文件,即通过{{1}访问Fetch API cannot load file:///C:/your/path/to/data.json. URL scheme "file" is not supported.文件,则将始终出现错误 JSON }协议,而不是file:///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');

原因再次是协议和跨源问题,这限制了您访问文件。

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


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

  1. 通过键入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.
  2. 安装http服务器
  3. 切换到您的工作目录,其中npm install -g http-server居住
  4. 通过发出yoursome.html
  5. 来启动http服务器

这将运行Node.js http-server -c-1,该目录将您目录中的文件作为可从httpd访问的静态文件提供服务

本文链接:https://www.f2er.com/3157038.html

大家都在问