skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    1. Use a Browser Extension: Some browser extensions can override CORS policies for local files during development.
    2. Use a Different Browser: Try using a browser that has less strict CORS policies in its local file handling.
    3. Consider a Local Development Server: While a full web server might not be feasible, there are lightweight local development servers that you can run without installing anything globally. For example, you can use tools like http-server or live-server via Node.js.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search