我尝试在本地主机上使用 fetch
,但没有用。
这是我的代码:
<!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 文件与脚本文件位于同一文件夹中。
控制台中显示以下错误:
index.html:12 Fetch API cannot load file:///C:/~~~~/hi.txt. URL scheme "file" is not supported.
(~~~) 是路径
原文由 UiJin 发布,翻译遵循 CC BY-SA 4.0 许可协议
由于您的 URL 是相对的(它只是
"hi.txt"
),它是根据运行代码的页面的 URL 解析的。在您的情况下,这似乎是file:///something
— 也就是说,您直接从文件系统加载的文件,而不是通过从服务器请求它。 Chrome 不允许从file
方案中获取。file
方案的起源是null
。 Chrome 团队对同源 政策 的解释是,任何来源,甚至它本身,都不应匹配null
。 (我认为这是一个合理的解释,但意见可能会有所不同。)在进行 Web 开发时,您希望通过服务器进程进行工作,因为直接从文件系统加载的页面与从服务器加载的页面在一些有时微妙的方式上表现不同。
有几种方法可以做到这一点:
npm
(和 Node.js),使用一个命令可以在开发模式下在本地构建和运行项目.