gpt4 book ai didi

javascript - 访问 ' from origin ' null 处的脚本已被 CORS 策略阻止

转载 作者:可可西里 更新时间:2023-11-01 02:37:29 26 4
gpt4 key购买 nike

因此,当我尝试从另一个 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);
}
}

我使用的是 chromium 浏览器。我的文件夹结构如下所示:

/javascript
-/src
-index.js
-paddle.js
-index.html

有人知道如何避免 cors 策略吗?

最佳答案

ES6 模块遵循同源策略。您需要从本地服务器运行您的脚本,直接用浏览器打开文件是行不通的。

看这里ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error

关于javascript - 访问 ' from origin ' null 处的脚本已被 CORS 策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com