首页 > 解决方案 > 在 html 中将 js 文件作为模块导入会在 firefox 中出现 CORS 错误

问题描述

我有一个简单的 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”.

标签: javascripthtmlimport

解决方案


根据这篇文章,运行模块需要一个 HTTP(s) 连接,并且不能在本地工作:

如果您尝试通过 file:// 协议在本地打开网页,您会发现导入/导出指令不起作用。使用本地 Web 服务器,例如静态服务器或使用编辑器的“实时服务器”功能,例如 VS Code Live Server Extension 来测试模块。

因此,我会确切地建议您不要在本地运行它,而是使用您喜欢的文本编辑器中的实时服务器扩展。


推荐阅读