问题描述:
编写代码,要求html从外部文件stu.csv中获取数据到网页中
<!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>
<!-- 载入D3库 -->
<script src="d3.v3.min.js"></script>
</head>
<body>
<script type="text/javascript">
d3.csv("stu.csv",function(data){
console.log(data);
});
</script>
</body>
</html>
控制台报错:
Access to XMLHttpRequest at 'xxx' 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. index.html:18 null stu.csv:1 Failed to load resource: net::ERR_FAILED
报错原因:
因载入其他文件的需要(图片、csv、json等文件),需针对存有网站文件的本地文件夹启动一个Web服务
解决方案:
方式1 使用Python启动Web服务
具体步骤:
1)首先 win+R输入cmd进入命令提示符,然后在命令控制台中切换到你要导入的文件所在的文件夹
2)如果安装的python版本是python2,则在命令提示符中输入python -m SimpleHTTPServer;如果python版本是python3,则输入python -m http.server
3)通过http://localhost:8000访问网页,报错消失
4)如需自定义端口,假设为8001,命令可改为: python -m SimpleHTTPServer 8001
方法二 使用Visual Studio Code插件启用Web服务
具体步骤:
1)在Visual Studio Code中查找Preview on Web Server插件,并安装
2) 选择html文件,点击右键,选择vscode-preview-server: Launch on browser,网页正常显示,不会报错