Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

javascript - Access to Script at ' from origin 'null' has been blocked by CORS policy

So when I am trying to import class from another javascript file, I am getting error in console like this:

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:

<script type="module" src="src/index.js"></script>

My index.js looks like this:

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:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...