CORS 策略已经阻止了从原始“ null”访问“ at”的脚本

因此,当我试图从另一个 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 政策吗?

110975 次浏览

ES6 modules are subject to same-origin policy. You need to run your script from a local server, opening the file directly with a browser will not work.

see here ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error

file:// requests will not work, but you can run a local webserver (polymer serve, express, etc.) to use HTTP requests instead. You could even use the following Chrome extension to run a local webserver.

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en

Looks like you're trying to open the web-page locally (via file:// protocol) i.e. double clicking the .html file. Unfortunately modules only work via HTTP(s), so all you need to do is use a local web server. Popular choices include:

  • Live Server, a VS Code extension that adds a right-click option to run your pages with a local server.

  • Node static server, a simple http server to serve static resource files from a local directory.

  • Node live server is easy to install and use:

    npm install -g live-server // Install globally via npm
    live-server                // Run in the html's directory
    

Official MDN documentation mentions about running local .html files with js onboard leads to the CORS error. For more details look "JavaScript Modules" documentation page.

"Other differences between modules and standard scripts" section says:

You need to pay attention to local testing — if you try to load the HTML file locally (i.e. with a file:// URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server.