Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
Suule Avatar asked Oct 21 '18 20:10

Suule


People also ask

How do I fix origin Null has blocked by CORS policy?

From Origin 'null' Has Been Blocked By CORS Policy Error. To fix this error is also easy, what you need to do is to create a local web server, and then upload the Html and JS file to the webserver.

How do I fix a blocked CORS policy?

Use a Chrome extension to add Access-Control-Allow-Origin header into every response. To find one of them, just head over to Chrome Webstore and type in "CORS", dozens will show up in the search result. Or you can install CORS Helper, CORS Unblock or dyna CORS right away.

How do I fix CORS policy no Access-Control allow origin?

< access-control-allow-origin: * You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it! Thanks this helps to avoid all the hassle and test the code from localhost.


1 Answers

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

like image 118
Taha Azzabi Avatar answered Sep 18 '22 22:09

Taha Azzabi