UiJ*_*Jin 15 javascript asynchronous es6-promise fetch-api
我尝试在本地主机上使用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>
Run Code Online (Sandbox Code Playgroud)
hi.txt 文件与脚本文件位于同一文件夹中。
控制台中显示以下错误:
index.html:12 Fetch API cannot load file:///C:/~~~~/hi.txt. URL scheme "file" is not supported.
(~~~) 是路径
T.J*_*der 19
由于您的 URL 是相对的(它只是"hi.txt"
),因此它会根据代码运行所在页面的 URL 进行解析。在您的情况下,这似乎是file:///something
\xc2\xa0\xe2\x80\x94 ,即,您直接从文件系统加载的文件,而不是通过从服务器请求它。Chrome 不允许从该file
方案中获取数据。该file
方案的起源是null
。Chrome 团队对同源政策的解释是,任何来源(甚至自身)都不应该匹配null
。(我认为这是合理的解释,但意见可能会有所不同。)
在进行 Web 开发时,您希望通过服务器进程进行工作,因为直接从文件系统加载的页面与从服务器加载的页面在一些有时甚至是微妙的方式上的行为有所不同。
\n有几种方法可以做到这一点:
\nnpm
,并使用可用于在开发模式下本地构建和运行项目的命令。 归档时间: |
|
查看次数: |
44559 次 |
最近记录: |