【发布时间】:2019-03-25 22:29:56
【问题描述】:
因此,当我尝试从另一个 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);
还有 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);
}
}
我正在使用铬浏览器。我的文件夹结构如下:
/javascript
-/src
-index.js
-paddle.js
-index.html
有人知道如何避免 cors 政策吗?
【问题讨论】:
-
你想在 file-protocoll 上做一个网站吗?你需要一个服务器,然后你可以为 cors 设置允许标头
-
@johnSmith 为什么我需要从服务器运行 javascript 客户端代码?
-
js 仍将在您的浏览器(客户端)中执行,但如果您运行本地服务器来“提供”文件,您可以通过浏览器通过 http 协议访问它们,您不会出现该错误您正在遇到并且您更接近实际的网络基础设施