56

I am trying to understand modules in JavaScript but when I try to write a very simple module I get CORS error.I am using bracket as my text editor and the odd part is when I'm using live preview in brackets the code works but when I normally open the .js file I get error.

index.html

<!DOCTYPE html>
    <html>
    <head>
        <title> JS </title>
    </head>
    <body>
        <script type="module">
            import {add} from './libA.js'; 
            console.log(add(10,20));
        </script>
    </body>
    </html>

libA.js

export function add(a,b) {
        return a+b ;
    }

*I get this error ->

Access to Script at 'file:///F:/WEB%20DEV/JavaScript/libA.js' from origin `null` has been blocked by CORS policy: 
Invalid response. 
Origin 'null' is therefore not allowed access.

(I even tried the latest version of chrome too)

QuickSilver
  • 3,915
  • 2
  • 13
  • 29
Ahmad Reza
  • 863
  • 1
  • 7
  • 13

4 Answers4

45

Many browsers do not allow you to access files on the local filesystem with JavaScript (even if the HTML document is also on the local filesystem).

This extends to loading JavaScript modules.

Install a webserver and use that (with a URL like http://localhost/) for testing.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
7

If you have node installed I would recommend installing http-server package. You'll be up and running in no time! Fixed my problem and I can run my application in chrome using the server.

fUrious
  • 434
  • 5
  • 14
  • Please elaborate ! – Trunk Feb 21 '20 at 20:28
  • *Please elaborate !* ~ * ~ Instead of **http-server** you may want to try **live-server**. See for example [install and run a local web server](https://stackoverflow.com/a/62533794). – Henke Mar 26 '21 at 11:57
-2

I had the same, removed the type="module" and then the error was gone. Not sure why.

Rob van Daal
  • 298
  • 1
  • 9
  • 16
    If you remove `type=“module”` then the JS will throw an error when it hits `import` – Quentin Dec 19 '21 at 09:20
  • 3
    @Quentin how do you `import` (so ES6 code doesn't complain about missing class) and not get CORS ? I can ` – Alain Dumesny Feb 20 '22 at 09:05
-11

install apache it will have more uses in the future. avoid instead of using third party application like nodejs and sub thid party mini frameworks is a headache. Once you run apache you can run modules. with no nodejs required to be opened

vincent thorpe
  • 171
  • 1
  • 10