最佳答案
因此,当我试图从另一个 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 文件中,我以这种方式添加脚本文件:
<script type="module" src="src/index.js"></script>
我的 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);
还有桨:
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);
}
}
我用的是铬浏览器,我的文件夹结构是这样的:
/javascript
-/src
-index.js
-paddle.js
-index.html
有人知道怎么避免 Cors 政策吗?