Search code examples
javascriptasynchronouses6-promisefetch-api

fetch api cannot load, url scheme 'file' is not supported


i tried to use fetch on localhost, but it didn't work.

here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        fetch("hi.txt").then(function(response){
            response.text().then(function(text){
                alert(text)
            })
        })
    </script>
</body>
</html>

hi.txt file is in same folder with the script file.

below error is shown in console:

index.html:12 Fetch API cannot load file:///C:/~~~~/hi.txt. URL scheme "file" is not supported.

(~~~) is path


Solution

  • Since your URL is relative (it's just "hi.txt"), it's resolved against the URL of the page the code is running in. In your case, that appears to be file:///something — that is, a file you've loaded directly from your file system, not by requesting it from a server. Chrome doesn't allow fetching from the file scheme. The file scheme's origin is null. The Chrome team's interpretation of the Same Origin Policy is that no origin, not even itself, should match null. (A reasonable interpretation in my view, but opinions can vary.)

    When doing web development, you want to be working through a server process because pages loaded directly from the file system behave differently in several sometimes-subtle ways vs. pages loaded from servers.

    There are a couple of ways to do that:

    • Use the features of your IDE, if you use one, and/or extensions to it. For instance, for VSCode there's the "live server" extension which makes it very easy to run your code from a minimal server.
    • Use an actual web server process running locally. There are simple ones that are easy to install.
    • Use one of various "quick start" scaffolding tools that set up simple projects for you, often via npm (and Node.js), with a command you can use to build and run the project locally in development mode.