javascript modules and CORS

2019-01-29 03:18发布

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 Im 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 try the latest version of chrome too)

2条回答
我想做一个坏孩纸
2楼-- · 2019-01-29 03:35

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-29 03:50

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).

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

查看更多
登录 后发表回答