javascript - Fetch API 无法加载 file:///C:/Users/(文本文件“data.txt”的路径)。对于 CORS 请求,URL 方案必须是“http”或“https”。(微软边缘)
问题描述
这是test.html
我写的:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My Home Page</title>
</head>
<body>
<script src="test.js"></script>
</body>
</html>
这是test.js
:
fetch("example/data.txt").then(response => {
console.log(response.status);
console.log(response.headers.get("Content-Type"));
});
这是我从 Microsoft Edge 保存的错误:
test.js:1 Fetch API cannot load file:///C:/Users/pp/Github/Javascript_Work/testing/example/data.txt. URL scheme must be "http" or "https" for CORS request.
(anonymous) @ test.js:1
test.js:1 Uncaught (in promise) TypeError: Failed to fetch
at test.js:1
(anonymous) @ test.js:1
Promise.then (async)
(anonymous) @ test.js:1
解决方案
出于安全原因,您无法加载本地文件。您应该在网络服务器上提供文件,然后您可以对它们提出请求,或者您可以使用文件的输入类型,以便用户可以上传有关文件。
请参阅:https
://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp
如果您对安全原因感兴趣,可以点击此链接:
https://security.stackexchange。 com/questions/201208/why-do-browsers-disallow-accessing-files-from-local-file-system-even-if-the-html
如果 HTML 页面中的 JavaScript 在文件系统上打开时可以访问内容文件系统,那么它可以轻松地将该数据上传到网络服务器。然后,攻击者需要做的就是诱使用户打开下载的 HTML 文档,然后他们就拥有了您的私人数据。
推荐阅读
- php - 尝试使用 composer 将 sylius/product-bundle 安装到我的 Symfony 5.3 项目时出现问题
- apache-spark - 如何根据索引组合生成数据集?
- sql - LIKE 运算符两列 clickhouse
- flutter - 在哪里初始化块?
- flutter - 在颤动中更改单个导航栏项(BottomNavigationBarItem)的样式?
- database - sqflite - 在 null 上调用了方法“插入”
- java - 在 Linux(不是 Ubuntu 或 Debian)上运行 Java Swing 应用程序的步骤是什么?
- sas - SAS:如果没有数据,ODS Excel 会锁定文件
- node.js - 在 VS Code 中键入 npm install 时出现错误
- c++ - 有限循环以不寻常的方式中断+图像