Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

javascript - ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error

Index.html

<html>
    <head>
    <script type="module">
        import {answer} from './code.js'
        console.info("It's ${answer()} time!")
    </script>
    </head>
    <body>
    </body>
</html>

code.js

export function answer(){
    return 'module';
}

Error: Access to Script at 'file:///C:*******/es6/code.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.

Chrome says it can support modules and I have seen examples working on the web, but when I copy them of download and run them locally, I always get the error above. I do not want to use Babel, Webpack, etc.

I have tried enabling the Experimental Web Platform features flag in both Chrome and Chrome Canary.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unlike regular scripts, ES6 modules are subject to same-origin policy. This means that you cannot import them from the file system or cross-origin without a CORS header (which cannot be set for local files).

Basically you need to run this code from a (local) server or disable same-origin in the browser for testing (do not do this permanently). See: Access to Image from origin 'null' has been blocked by CORS policy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...