【发布时间】:2018-10-02 22:30:40
【问题描述】:
我有以下两个文件:
index.html
<html>
<head>
<meta charset="utf-8" />
<title>Web Page</title>
<style type="text/css">
.text {
display: inline-block;
font-family: tahoma;
font-size: 14px;
max-width: 400px;
background-color: #ddedff;
padding: 10px;
text-align: justify;
}
</style>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
get_data('info.txt');
});
function get_data(file) {
var request = new Request(file);
fetch(request).then(function(response) {
return response.text().then(function(text) {
$('.text').html(text);
});
});
}
</script>
</head>
<body>
<div class="text"></div>
</body>
<html>
info.txt
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
当我在Mozilla Firefox 上打开文件时:README.html 通过这个本地URI:
file:///C:/testing/README.html
它按预期工作,我的意思是,文件中的文本:info.txt 正确显示。
但是当我在Google Chrome 上打开相同的URI 时,我得到一个空白屏幕,并且控制台上出现以下错误:
README.html:26 Fetch API cannot load file:///C:/testing/README.md. URL scheme must be "http" or "https" for CORS request.
get_data @ README.html:26
README.html:26 Uncaught (in promise) TypeError: Failed to fetch
at get_data (README.html:26)
at HTMLDocument.<anonymous> (README.html:21)
at l (jquery.min.js:2)
at c (jquery.min.js:2)
您有什么办法可以像在Mozilla Firefox 上一样打开Google Chrome 上的本地文件吗?
如果我必须做一些调整:
chrome://flags/
这对我来说是可以接受的。
编辑
我尝试从命令行启动Google Chrome 并使用标志:--allow-file-access-from-files,推荐here,但现在我收到以下错误:
README.html:26 Fetch API cannot load file:///C:/testing/README.md. URL scheme "file" is not supported.
get_data @ README.html:26
README.html:26 Uncaught (in promise) TypeError: Failed to fetch
at get_data (README.html:26)
at HTMLDocument.<anonymous> (README.html:21)
at l (jquery.min.js:2)
at c (jquery.min.js:2)
谢谢!
【问题讨论】:
-
您的问题的答案在 Chrome 提供的错误消息中。出于安全原因,Chrome 不允许您通过
file:///...加载本地文件。如果这是您正在开发的仅在本地使用的应用程序,那么您可以下载一个 Chrome 应用程序,该应用程序会在某个本地目录中为您创建一个 Web 服务器。 Chrome 的 Web 服务器是 Google 在其代码实验室工作时建议使用的服务器 -
没有
chrome://flags/调整,只有命令行调整。使用命令行选项启动 chrome,允许file:///页面访问file:///这样的资源 - 我不知道该选项,快速谷歌搜索应该会有所帮助 -
现在 Chrome 的
fetch似乎无法与file://URL 方案一起使用。你考虑过 XHR 吗?或者,更好的是,使用本地 http 服务器? -
@Jaromanda,谢谢,成功了
标签: javascript google-chrome firefox fetch-api file-uri