Javascript CORS 策略已阻止访问 ' from origin 'null' 处的脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52919331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access to Script at ' from origin 'null' has been blocked by CORS policy
提问by Suule
So when I am trying to import class from another javascript file, I am getting error in console like this:
因此,当我尝试从另一个 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.
In my html file I am adding script file in this manner:
在我的 html 文件中,我以这种方式添加脚本文件:
<script type="module" src="src/index.js"></script>
My index.js looks like this:
我的 index.js 看起来像这样:
import Paddle from "/src/paddle";
let canvas = document.getElementById("gameScreen");
let ctx = canvas.getContext("2d");
const GAME_WIDTH = 800;
const GAME_HEIGHT = 600;
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
let paddle = new Paddle(GAME_WIDTH, GAME_HEIGHT);
paddle.draw(ctx);
And paddle.js:
和 paddle.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);
}
}
I am using chromium browser. And my folder structure looks like:
我正在使用铬浏览器。我的文件夹结构如下所示:
/javascript
-/src
-index.js
-paddle.js
-index.html
Anyone has any idea how to avoid cors policy?
任何人都知道如何避免 cors 政策?
采纳答案by Taha Azzabi
ES6 modules are subject to same-origin policy. You need to run your script from a local server, open directly the file with a browser will not work.
ES6 模块遵循同源策略。你需要从本地服务器运行你的脚本,用浏览器直接打开文件是行不通的。
see here ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error

