首页 > 其他分享> > ES6模块化遇到的跨源问题Access to script at ‘X.js‘ from origin ‘null‘ has been blocked by CORS policy... 解决方法
ES6模块化遇到的跨源问题Access to script at ‘X.js‘ from origin ‘null‘ has been blocked by CORS policy... 解决方法
作者:互联网
a.js中使用export导出flag,sum:
let flag = true;
function sum(num1, num2) {
return num1 + num2
}
if (flag) {
console.log(sum(1, 2));
}
export {
flag,
sum
}
b.js中使用import导入flag,sum:
import { flag, sum } from './a.js';
console.log(flag);
if (flag) {
console.log(sum(100, 200));
}
index.html引入a.js、b.js:
<!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" src="./a.js"></script>
<script type="module" src="./b.js"></script>
</body>
</html>
直接在浏览器中预览时报错:跨源请求仅支持协议方案
解决方法:
在VSCode中安装live server插件:
在index.html文件中右键:“Open with Live Server”,正常输出结果:
标签:origin,ES6,console,log,跨源,js,flag,sum,num1 来源: https://blog.csdn.net/u010234868/article/details/121393320