错误描述
Access to script at ‘file:///Users …’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
跨域原因
- 在没有启用服务器直接本地打开的文件,浏览器并不支持file协议
- http, data, chrome, chrome-extension, https这些协议是支持跨域请求的
解决方案:
如果你尝试用本地文件加载 HTML 文件 (i.e. with a file:// URL),由于 JavaScript 模块的安全性要求,你会遇到 CORS 错误。你需要通过服务器来做你的测试。GitHub pages is ideal as it also serves .mjs files with the correct MIME type.
VSCode —> 安装插件Live Server ----> HTML文件中右键菜单选择 Open with live server