【发布时间】:2019-08-19 07:51:11
【问题描述】:
我正在制作一个简单的测试项目,包括 2 个 JavaScript 文件,我在其中导出和导入模块,如下所示。
但是,当打开 html 页面时,控制台中生成的错误显示:
Access to script at 'file:///C:/Users/index2.js' from origin 'null' has been blocked by CORS policy Failed to load resource: net::ERR_FAILED (index2.js:1)
我尝试停用 CORS,但这总是导致相同的错误,我使用的是 Google Chrome 浏览器。
代码中有什么异常以及如何解决这个问题?
index2.js:
export default class test {
static method () {
return ('hello world' ) ;
}
index.js:
import test from './index2.js';
console.log (test.method()) ;
在 index.html 中:
<script type = "module" src="./index.js"></script>
【问题讨论】:
-
你在使用任何构建工具吗? webpack 等?
-
大多数浏览器不允许您使用 JS 访问本地文件系统上的文件。您将需要设置本地网络服务器并从那里访问文件。看看这篇文章:stackoverflow.com/q/50197495/5347875
-
aviya.developer 不,我在这个例子中没有使用构建工具,@Daniel.Schroeder 有什么建议吗?谢谢。
标签: javascript cors