javascript - 在 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”.
解决方案
根据这篇文章,运行模块需要一个 HTTP(s) 连接,并且不能在本地工作:
如果您尝试通过 file:// 协议在本地打开网页,您会发现导入/导出指令不起作用。使用本地 Web 服务器,例如静态服务器或使用编辑器的“实时服务器”功能,例如 VS Code Live Server Extension 来测试模块。
因此,我会确切地建议您不要在本地运行它,而是使用您喜欢的文本编辑器中的实时服务器扩展。
推荐阅读
- typescript - 仅使用键创建 Javascript 对象以进行类型安全的 graphql 查询
- reactjs - 用 redux 存储记住我
- python - 比较两个不同大小的列表并返回 bool-list
- android - android emulator sdk 10 api 29 重新挂载并重启后不会启动
- windows - 如何使用命令行将 Windows 时间与服务器同步?
- php - 目录的 .htaccess 中的 RewriteRule 会破坏一般的 404 ErrorDocument 并创建 500
- javascript - 从文件修改json对象并保持结构
- javascript - Ionic 4 firebase 电话身份验证将新用户重定向到特定页面
- email - SMTP 邮件服务在 AEM 6.4(Service Pack 7)中不起作用 - 邮件服务配置无效
- php - Artisan 队列处理过程挂起