Chrome 62/Chrome Canary 64 中的 ES6 模块支持,在本地不起作用,CORS 错误 [英] ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error

查看:34
本文介绍了Chrome 62/Chrome Canary 64 中的 ES6 模块支持,在本地不起作用,CORS 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

索引.html

<头><脚本类型=模块">从./code.js"导入{答案}console.info("现在是 ${answer()} 时间!")<身体>

code.js

导出函数 answer(){返回模块";}

<块引用>

错误:从源null"访问file:///C:*******/es6/code.js"处的脚本已被 CORS 策略阻止:响应无效.因此,不允许访问原点 'null'.

Chrome 说它可以支持模块,我在网上看到过一些示例,但是当我复制下载的它们并在本地运行它们时,我总是得到上面的错误.我不想使用 Babel、Webpack 等.

我已尝试在 Chrome 和 Chrome Canary 中启用实验性网络平台功能标志.

解决方案

与常规脚本不同,ES6 模块受 同源政策.这意味着您不能在没有 CORS 标头(不能为本地文件设置)的情况下从文件系统或跨域import它们.

基本上,您需要从(本地)服务器运行此代码或在浏览器中禁用同源以进行测试(不要永久执行此操作).请参阅:从源访问图像'null' 已被 CORS 政策阻止.

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.

解决方案

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.

这篇关于Chrome 62/Chrome Canary 64 中的 ES6 模块支持,在本地不起作用,CORS 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆