112

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?

Suule
  • 2,197
  • 4
  • 16
  • 42
  • you want to make a website on file-protocoll? you need a server then you can set the allow header for cors – john Smith Oct 21 '18 at 20:17
  • 8
    @johnSmith Why do I need to run javascript client-side code from server? – Suule Oct 22 '18 at 07:18
  • 3
    the js will still execute in your browser (client-side) but if you run a local server to "serve" the files you can access them through the browser via http protocoll and you wont have that error you are encountering and you are more close to actual web-infrastructure – john Smith Oct 22 '18 at 08:43
  • 1
    Possible duplicate of [ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error](https://stackoverflow.com/questions/46992463/es6-module-support-in-chrome-62-chrome-canary-64-does-not-work-locally-cors-er) – Gaurang Tandon Dec 16 '18 at 04:38

8 Answers8

82

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

ahmadPH
  • 135
  • 11
Taha Azzabi
  • 2,392
  • 22
  • 31
65

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

Or even shorter and without altering your packages:

npx live-server
Randy
  • 9,419
  • 5
  • 39
  • 56
Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153
6

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

Vibhor Dube
  • 4,173
  • 1
  • 22
  • 32
5

If you don't want to set up a local server you can actually (contrary to the previous answers) use the file:// protocol. To do so you have to run your browser with the --allow-file-access-from-files flag. Should work in all chromium based browsers such as Chrome, Opera, Brave etc.

Joel Sahlin
  • 51
  • 1
  • 7
  • I am running chrome with this option, but still getting the CORS error when loading a script with `type="module"`. – kgilpin Feb 28 '23 at 21:34
  • How exactly did you start chrome? Also are you sure you get the exact same error? The file protocol uses relative paths, which can often lead to errors when using modules that doesn't have paths specified in a relative way. – Joel Sahlin Mar 01 '23 at 22:27
  • I want to clarify that you can't have any previous windows opened in your browser when doing this, as the permissions get set when first starting the sandbox. Make sure all instances of your chromium based browser is closed first, or it won't change the permissions to allow the `file://` protocol. – Joel Sahlin Apr 02 '23 at 21:48
  • 1
    Thank you, works great even as a Linux Mint 'Webapp', where one can indicate an extra parameter for Chromium. – Moini Apr 25 '23 at 01:23
1

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.

hamsternik
  • 1,376
  • 3
  • 18
  • 26
0

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. Then you can browse the Html file in the web browser with the HTTP or HTTPS protocol, and then it will also load the external JS file using the HTTP or HTTPS protocol also. soloving:

1- First of all Go to the extension and download Live Server. 2- Press F1 and enter Live Server and choose Open with Live Server from menu and there you go :)

0

I faced the same issue: enter image description here

Resolution:

Installed the lite-server to load the files:

  • Lite-Server:BrowserSync does most of what we want in a super fast lightweight development server. It serves the static content, detects changes, refreshes the browser, and offers many customizations.

    npm i lite-server
    

include below code in package.json

"scripts": {
    "start": "lite-server"
  },

Now instead of using open / start use npm start

-3

I think if you are on phone, you can use File Manager Plus, and open the HTML file with app that have an HTTP icon in right.

Rindo
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '23 at 08:41
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33963551) – Alijvhr Mar 09 '23 at 14:57