CORS跨域问题解决
背景
想在本地跑一下CodePen导出的项目,直接将html文件view in browser无法显示动态控件,F12看了下网络信息发现是本地js请求报错
控制台错误信息如下
Access to script at ‘file:///K:/frontCodeLearning/3d-carousel/dist/script.js’ 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-untrusted, https, edge.
原因
查了下原因,发现是浏览器自带跨域资源访问(CORS)有域名限制,请求必须以HTTP或HTTPS开头,即不能直接访问本地js文件
解决方法
将要访问的文件托管到服务器上,再发送HTTP请求进行访问
这里我是把js文件放在了github.io上
html文件里访问js的url改为
<script type="module" src="https://jasmine0722.github.io/js/3d/script.js"></script>
注意:这里的url不能直接用js文件的链接地址https://github.com/Jasmine0722/Jasmine0722.github.io/blob/main/js/3d/script.js
问题解决,撒花!!
效果演示
看下效果吧