I have been trying to access a local json file in javaScript using fetch (as shown below).
fetch('./js/data.json')
.then(response => response.json())
.then((data) => {
console.log(data);
})
.then((error) => {
console.log(error);
});
I found out from this that I can not access the json file localy and not to access it from a https sever on localhost.
I set this up using ngrok.
fetch('https://a9f8-86-133-120-217.ngrok.io/js/data.json', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}) .then(response => response.json())
.then((data) => {
console.log(data);
})
.then((error) => {
console.log(error);
});
When I now run the code I get the following errors.
[Error] Preflight response is not successful. Status code: 501
[Error] Fetch API cannot load https://a9f8-86-133-120-217.ngrok.io/js/data.json due to access control checks.
After some research, I found this was due to working called cors.
I then added mode: 'no-cors' to my code. This then meant that the JSON file was being fetched but it was casing more error.
Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.
The error is from the following line.
.then(response => response.json())
When I remove 'Content-Type': 'application/json' I get the following error.
Origin null is not allowed by Access-Control-Allow-Origin. Status code: 200
I have been trying to fix this for a few hours but have had no luck.
I feel this is something so simple that I'm missing.