我尝试在本地主机上使用 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:
npm
(和 Node.js),您可以使用命令在开发模式下在本地构建和运行项目.npm
(and Node.js), with a command you can use to build and run the project locally in development mode.这篇关于fetch api 无法加载,不支持 url 方案“文件"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!