javascript - 使用 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 文件?
- 我在代码中缺少什么?
示例 .json
[
{
"country": [
{
"name": "Spain",
"GDP": " $1234",
"Regions": " Europe ",
"Align": " Western "
}
]
}
]
有类似问题但解决方案不同的人,或者对我没有用
进一步解释以了解问题
我正在工作的文件夹如下所示:
节点模块
索引.html
国家球.json
我正在使用 Node.js 和 Visual Studio Code
- index.html 使用 Chrome 浏览器在 localhost:8080 上运行
我考虑过的可能解决方案
- 使用文件系统加载它(但仍想尝试 fetch())
问题的图片库
(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
解决方案
推荐阅读
- java - 执行 selenium 测试时浏览器未在 Jenkins 中打开
- types - 使用 Prolog 进行类型检查
- android - 为什么 Kotlin 数组不返回计数
- vue.js - 数据太大,无法在移动版图表上显示
- azure-iot-hub - 配置 MAX_OPERATION_TIMEOUT
- entity-framework-core - 如何使用 Entity Framework Core 2.2 播种自引用树
- c++ - 如何将公共方法中的数据添加到同一类中的私有成员数组中?
- javascript - 如何在 index.html 中添加的所需路由上显示/隐藏“共享此按钮 html”
- conv-neural-network - CNN 中的反向传播如何用于文本分类中的预训练嵌入
- google-bigquery - 如何在bigquery中按天计算(非)连续记录?