Introduction
I have a local file 'countryballs.json'
which I want to load it on a html and parse the data into the index.html
.
The way I want to do it, and the only one I know, it's by using Fetch(). Quite easy to use.
Code
async function getData()
{
await fetch('./countryballs.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
})
.catch(function (error) {
console.log(error);
})
}
getData();
Code explanation
Fetch should be used in a async function as it returns a promise (loading files takes time)
await fetch() //Will wait until all has being loaded. The rest of the code is self-explanatory ES6 JS coding.
Problem
When working with external API's (for weather, finance and stuff) it just works perfectly, I can retrieve and parse the data and everything goes well. Even loading local CVS files. But not with my local JSON file.
ERROR
index.html:15 GET http://localhost:8080/countryballs.json 404 (Not Found)
XMLHttprequest log:
index.html:15 Fetch failed loading: GET "http://localhost:8080/countryballs.json".
Questions
- Why it does not work with JSON files too?
- What I am missing in the code?
Example .json
[
{
"country": [
{
"name": "Spain",
"GDP": " $1234",
"Regions": " Europe ",
"Align": " Western "
}
]
}
]
People with similar problems but different solutions or it didn't worked for me
Further explanation to understand the problem
The folder where I am working looks like this:
node-modules
index.html
countryballs.json
I am using Node.js and Visual Studio Code
- The index.html runs on a localhost:8080 using Chrome Browser
Possible solution that I considered
- Using the File System to load it (but still want to try fetch())
Image gallery of the problem
(Chrome's console output)
Edit:
As some of you requested I will provide what I have here and below the instructions to test.
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