在 html 中将 js 文件作为模块导入会在 firefox 中出现 CORS 错误
Importing js file as module in html gives CORS errors in firefox
我有一个简单的 html 文件:
<html>
<head>
<meta charset="utf-8"/>
<title>Test</title>
</head>
<script type="module">
import init from './target/test.js'
init()
</script>
</html>
并且在目标文件夹中有一个 test.js
文件:
function init() {
console.log("It works");
}
export default init;
但是当我用 firefox 打开 html 文件时,我在控制台中收到以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/wanne/Bureaublad/hmm/target/test.js. (Reason: CORS request not http).
Module source URI is not allowed in this document: “file:///C:/Users/wanne/Bureaublad/hmm/target/test.js”.
根据 this article,运行 模块需要 HTTP(s) 连接并且不能在本地工作:
If you try to open a web-page locally, via file:// protocol, you’ll
find that import/export directives don’t work. Use a local web-server,
such as static-server or use the “live server” capability of your
editor, such as VS Code Live Server Extension to test modules.
所以我建议完全这样,而不是 运行 在本地,使用您喜欢的文本编辑器中的实时服务器扩展。
我有一个简单的 html 文件:
<html>
<head>
<meta charset="utf-8"/>
<title>Test</title>
</head>
<script type="module">
import init from './target/test.js'
init()
</script>
</html>
并且在目标文件夹中有一个 test.js
文件:
function init() {
console.log("It works");
}
export default init;
但是当我用 firefox 打开 html 文件时,我在控制台中收到以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/wanne/Bureaublad/hmm/target/test.js. (Reason: CORS request not http).
Module source URI is not allowed in this document: “file:///C:/Users/wanne/Bureaublad/hmm/target/test.js”.
根据 this article,运行 模块需要 HTTP(s) 连接并且不能在本地工作:
If you try to open a web-page locally, via file:// protocol, you’ll find that import/export directives don’t work. Use a local web-server, such as static-server or use the “live server” capability of your editor, such as VS Code Live Server Extension to test modules.
所以我建议完全这样,而不是 运行 在本地,使用您喜欢的文本编辑器中的实时服务器扩展。