1

I know this question is already there in stack overflow, but it's not relevant for my issue. I didn't get a solution.

I have two file index.html and data.json.

My code:

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <script>
            async function fun(){
                const res = await fetch('temp.json');
                const dat = await res.json();
                return      (Object.values(data));
            }
            console.log(fun());
        </script>
    </body>
</html>
{
"1": "One",
"2": "two",
"3": "Three"
}

I got the error mentioned in the title in my browser (firefox and mobile chrome). Console:

Promise { <state>: "rejected", <reason>: TypeError }
<state>: "rejected"
<reason>: TypeError: NetworkError when attempting to fetch resource.
<prototype>: Promise.prototype { … }

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///home/kashyap/Desktop/data.json. (Reason: CORS request not http).
7
  • As the error said 'Reason: CORS request not http' Commented Jun 21, 2022 at 11:03
  • Does this answer your question? Chrome - Fetch API cannot load file. How to workaround? Commented Jun 21, 2022 at 11:05
  • 2
    Are you running this from the file system? You should run it using a web server. Commented Jun 21, 2022 at 11:09
  • @angel.bonev nope... Commented Jun 21, 2022 at 11:14
  • 1
    Running from the file system does not work. Install a web server. I often use http-server - npm in a scenario like this. Commented Jun 21, 2022 at 11:17

1 Answer 1

0

As mentioned by @chrwahl in comment, we need to use a web server to solve this issue instead of file system. Because of security reason firefox doesn't allow that (not sure about other browsers).

I have moved the files to root folder of my web server (apache)(/var/www/html/ in linux and htdocs folder in Xamp).

The error has gone and promise has fulfilled.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.