首页 > 解决方案 > 使用 fetch 和 ES6 加载本地 JSON 文件

问题描述

介绍

我有一个本地文件'countryballs.json',我想将它加载到 html 上并将数据解析index.html.

我想做的方式,也是我唯一知道的方式,就是使用Fetch()。很容易使用。

代码

async function getData()
        {
            await fetch('./countryballs.json')
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                console.log(data);
            })
            .catch(function (error) {
                console.log(error);
            })
        }
        getData();

代码说明

Fetch 应该在异步函数中使用,因为它返回一个承诺(加载文件需要时间)

await fetch() //将等到所有内容都加载完毕。其余代码是不言自明的 ES6 JS 编码。

问题

当使用外部 API(用于天气、金融和其他东西)时,它运行良好,我可以检索和解析数据,一切顺利。甚至加载本地 CVS 文件。但不是我的本地 JSON 文件。

错误

index.html:15 GET http://localhost:8080/countryballs.json 404 (Not Found)

XMLHttp请求日志:

index.html:15 Fetch failed loading: GET "http://localhost:8080/countryballs.json".

问题

示例 .json

[
  {
    "country": [
      {
        "name": "Spain",
        "GDP": " $1234",
        "Regions": " Europe ",
        "Align": " Western "
      }
    ]
  }
]

有类似问题但解决方案不同的人,或者对我没有用

进一步解释以了解问题

我考虑过的可能解决方案

问题的图片库

(Chrome 的控制台输出)

希望你帮我找到解决办法

编辑:

正如你们中的一些人所要求的,我将在此处和下方提供测试说明。

谷歌驱动文件

1. Get node.js
2. cd into the folder with the index.html and the rest
3. call for `node http-server`
4. get into the browser and connect to localhost:8080 

标签: javascriptjsonfetches6-promise

解决方案


推荐阅读