I am creating a project in which I have two files index.html and data.json.
Now I want to fetch the JSON object into index.html for rendering.
But I am encountering cors error if I use fetch()
method.
Is there any way to get the data from data.json ?
async fetchData(filename) {
try {
const response = await fetch(url);
const jsonData = await response.json();
return jsonData;
} catch (error) {
console.error('Error fetching data:', error);
}
}
2
Answers
Are you opening the html file directly by double clicking? (The URL in your browser would look like this: file:///C:/Users/username/project/index.html)
The problem is that fetching ./data.json would access your file system which is prohibited due to security reasons. If you are using visual studio code you can install the "live server" plugin. With that installed you could open your project as a folder in vscode and then right click on the index.html and choose "open with live server". After that the plugin should open your page in a new tab and the fetch call should be working, because the plugin is creating a static file server that serves your project files.
When working with local files using the
file://
protocol, modern browsers often enforce security restrictions, including CORS (Cross-Origin Resource Sharing) policies. These restrictions are in place to prevent potential security vulnerabilities. Unfortunately, there’s no direct way to disable or bypass CORS restrictions when loading local files via the file:// protocol.However, you may consider alternative approaches if using a web server is not feasible:
http-server
orlive-server
via Node.js.