0

Here is the test.html ,I wrote:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My Home Page</title>
    </head>
    <body>

        <script src="test.js"></script>
        
    </body>
</html>

Here is the test.js:

fetch("example/data.txt").then(response => {
    console.log(response.status);
    console.log(response.headers.get("Content-Type"));
});

Here is the error I saved from Microsoft Edge:

test.js:1 Fetch API cannot load file:///C:/Users/pp/Github/Javascript_Work/testing/example/data.txt. URL scheme must be "http" or "https" for CORS request.
(anonymous) @ test.js:1
test.js:1 Uncaught (in promise) TypeError: Failed to fetch
    at test.js:1
(anonymous) @ test.js:1
Promise.then (async)
(anonymous) @ test.js:1

1 Answers1

2

you can't load local files for security reason. you should serve files on web server then you can make requests for them or you can use input type of file so the user can upload regarding file.
see: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp

if you are interested in what's the security reason you can follow this link:
https://security.stackexchange.com/questions/201208/why-do-browsers-disallow-accessing-files-from-local-file-system-even-if-the-html

If JavaScript in an HTML page could access the contents file system when opened on the file system, it could easily upload that data to a webserver. Then all an attacker needs to do is trick the user into opening an HTML document that was downloaded, and then they have your private data.

Abdoljabbar
  • 574
  • 1
  • 6
  • 20