javascript Chrome 62/Chrome Canary 64 中的 ES6 模块支持,在本地不起作用,CORS 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46992463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error
提问by mark pavlis
Index.html
索引.html
<html>
<head>
<script type="module">
import {answer} from './code.js'
console.info("It's ${answer()} time!")
</script>
</head>
<body>
</body>
</html>
code.js
代码.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.
错误:从源“null”访问“file:///C:*******/es6/code.js”处的脚本已被 CORS 策略阻止:响应无效。因此,不允许访问 Origin 'null'。
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.
Chrome 说它可以支持模块,我在网上看到过一些例子,但是当我复制下载的它们并在本地运行它们时,我总是得到上面的错误。我不想使用 Babel、Webpack 等。
I have tried enabling the Experimental Web Platform features flag in both Chrome and Chrome Canary.
我尝试在 Chrome 和 Chrome Canary 中启用实验性 Web 平台功能标志。
回答by Alexander O'Mara
Unlike regular scripts, ES6 modules are subject to same-origin policy. This means that you cannot importthem from the file system or cross-origin without a CORS header (which cannot be set for local files).
与常规脚本不同,ES6 模块受同源策略的约束。这意味着您不能import在没有 CORS 标头(无法为本地文件设置)的情况下从文件系统或跨域中获取它们。
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.
基本上,您需要从(本地)服务器运行此代码或在浏览器中禁用同源以进行测试(不要永久执行此操作)。请参阅:从源 'null' 访问图像已被 CORS 策略阻止。
回答by Sydney C.
I've run in the same problem, trying to import es6 code to launch in a html file in my browser, getting CORS errors in my browser console. If you have python on your machine one easy way to create a local server is to:
我遇到了同样的问题,尝试导入 es6 代码以在浏览器的 html 文件中启动,在浏览器控制台中出现 CORS 错误。如果您的机器上有 python,创建本地服务器的一种简单方法是:
python3 -m http.server 8001
python3 -m http.server 8001
From the folder your are working in.
从您正在工作的文件夹中。

