首页 > 解决方案 > 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

标签: javascripthtmlnode.jsmicrosoft-edge

解决方案


出于安全原因,您无法加载本地文件。您应该在网络服务器上提供文件,然后您可以对它们提出请求,或者您可以使用文件的输入类型,以便用户可以上传有关文件。
请参阅: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 文档,然后他们就拥有了您的私人数据。


推荐阅读