引用import的JS报错:Access to script at 'file:' from origin 'null' has been blocked by CORS policy的解决方案
示例代码
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
import a from './a.js'; //报错行
console.log("a:", a)
</script>
</body>
</html>
a.js
console.log("a.js");
let a = 1;
export default a;
控制台报错
Access to script at 'file:///C:/Users/%E7%8E%8B%E6%82%A6/Desktop/websocket_test/a.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
别的浏览器都可以,而在唯独谷歌浏览器报错,原因大概是谷歌浏览器安全机制导致的,不允许在本地直接运行,会当作跨域访问。
解决方法
vs code 下载Live Server
插件
在html文件下,点击Go Live
运行html即可!