Cross origin in JavaScript import module

Viewed 1228

I have an index.html file that connect to file called main.js. I try to import another js file into the main.js using import, but always get the following error:

Access to script at 'file:///C:/...js/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I tried to open a server but it didn't solve the problem. I don't know if the problem is in my html file or js files and I really need your help.

My code goes like this:

index.html

<body>
    <script type="module" src='./js/main.js'></script>
</body>

main.js

import {
    double
} from './utils.js';

utils.js

export function double(n) {
    return n * 2;
}
1 Answers

You've probably fixed the problem by now, but for anyone googling in the future, here's the solution.

The error message says that you can't access the file from origin "null", and states that you can only do these requests with certain protocol schemes. The protocol scheme that local files on your computer have is "file://", and I think the origin: "null" thing is about it not being on a website (e.g. http://a.com vs file://a/b/c).

What you need to do to fix this is start a local server. The easiest approach is to use this python one-liner. If you are on MacOSX or Linux, go ahead and use the below command:

$ cd path/to/website
$ python -m SimpleHTTPServer 8080
Serving HTTP on 0.0.0.0 port 8000 ...

If you are on Windows, you need to install Python before making the server. To do so, go to the downloads page on their website and download the latest version. To check if it is installed, run this in the command prompt:

python -V

If you get something like Python 3.9.5, you can go ahead and run the command mentioned before.

Once you have got the server started, just navigate to http://localhost:8080/ in your browser.

Related