Javascript 访问位于'的脚本;来自原点';空';已被CORS策略阻止
所以,当我试图从另一个javascript文件导入类时,控制台中出现如下错误:Javascript 访问位于'的脚本;来自原点';空';已被CORS策略阻止,javascript,ecmascript-6,Javascript,Ecmascript 6,所以,当我试图从另一个javascript文件导入类时,控制台中出现如下错误: Access to Script at 'file:///home/../.../JavaScript/src/index.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access. 在我的html文件中,我以以下方式添加脚本文件: &
Access to Script at 'file:///home/../.../JavaScript/src/index.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.
在我的html文件中,我以以下方式添加脚本文件:
<script type="module" src="src/index.js"></script>
和paile.js:
export default class Paddle {
constructor(gameWidth, gameHeight){
this.width = 150;
this.height = 30;
this.position = {
x: gameWidth/2 - this.width/2,
y: gameHeight-this.height-10
}
}
draw(ctx){
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
}
}
我正在使用chromium浏览器。我的文件夹结构如下所示:
/javascript
-/src
-index.js
-paddle.js
-index.html
有人知道如何避免cors政策吗?ES6模块受同源政策约束。 您需要从本地服务器运行脚本,直接用浏览器打开文件将无法工作
请参见此处文件://请求将不起作用,但您可以运行本地Web服务器(polymer serve、express等)以使用HTTP请求。您甚至可以使用以下Chrome扩展来运行本地Web服务器
看起来您试图在本地打开网页(通过
文件://
协议),即双击.html
文件。不幸的是,模块只能通过HTTP工作,所以您所需要做的就是使用本地web服务器。受欢迎的选择包括:
- ,一个VS代码扩展,它添加了一个右键单击选项,以使用本地服务器运行页面
- ,一个简单的http服务器,为本地目录中的静态资源文件提供服务
- 易于安装和使用:
npm install -g live-server // Install globally via npm live-server // Run in the html's directory
npm install -g live-server // Install globally via npm
live-server // Run in the html's directory