fetch api 无法加载,不支持 url 方案“文件"

我尝试在本地主机上使用 fetch,但没有成功.

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

这是我的代码:

<!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 文件与脚本文件在同一文件夹中.

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

以下错误显示在控制台中:

below error is shown in console:

index.html:12 Fetch API 无法加载 file:///C:/~~~~/hi.txt.URL 方案文件"不支持.

(~~~) 是路径

推荐答案

由于你的 URL 是相对的(它只是 "hi.txt"),它是根据页面的 URL 解析代码正在运行.在您的情况下,这似乎是 file:///something - 也就是说,您直接从文件系统加载的文件,而不是通过从服务器请求它.Chrome 不允许从 file 方案中获取数据.file 方案的来源是 null.Chrome 团队对 Same Origin Policy 的解释是,任何来源,甚至其本身,都不应该匹配 <代码>空.(在我看来这是一个合理的解释,但意见可能会有所不同.)

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

在进行 Web 开发时,您希望通过服务器进程进行工作,因为直接从文件系统加载的页面与从服务器加载的页面相比,有时在一些微妙的方面表现不同.

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:

  • 使用 IDE 的功能(如果您使用其中之一)和/或它的扩展.例如,对于 VSCode,有实时服务器".扩展,让您可以非常轻松地从最小的服务器运行代码.
  • 使用在本地运行的实际 Web 服务器进程.有一些很容易安装的.
  • 使用各种快速启动"之一为您设置简单项目的脚手架工具,通常通过 npm(和 Node.js),您可以使用命令在开发模式下在本地构建和运行项目.
  • 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.

相关文章