132

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?

4
  • you want to make a website on file-protocoll? you need a server then you can set the allow header for cors
    – john Smith
    Commented Oct 21, 2018 at 20:17
  • 8
    @johnSmith Why do I need to run javascript client-side code from server?
    – Suule
    Commented Oct 22, 2018 at 7: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
    Commented Oct 22, 2018 at 8:43
  • 1

8 Answers 8

93

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

88

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
0
13

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.

4
  • 1
    I am running chrome with this option, but still getting the CORS error when loading a script with type="module".
    – kgilpin
    Commented Feb 28, 2023 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. Commented Mar 1, 2023 at 22:27
  • 2
    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. Commented Apr 2, 2023 at 21:48
  • 1
    Thank you, works great even as a Linux Mint 'Webapp', where one can indicate an extra parameter for Chromium.
    – Moini
    Commented Apr 25, 2023 at 1:23
7

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

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.

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

-5

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.

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.