读取本地xml或json等本地文件报错Failed to load file:///D:/xml/test.xml: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
问题如上图;
原因及解析:
在浏览器打开本地的html文件, 上面proxy中的url获取的就是一个本地文件, 协议是file://,如果是在服务器启动的话,则使用的是http或者https协议。
出于安全性考虑, Chrome默认禁止了这种用法,file协议和http/https协议不同,会被Chrome认为是跨域访问,所以会报被CORS(Cross-Origin Resource Sharing,跨域资源共享)的安全策略阻止。
原文链接:https://blog.csdn.net/oscar999/article/details/124114343
可以解决的方式是:
将Html文件挂在IIS上以网站方式去访问
读取本地xml文件参数,获取要得到的图片名,判断图片是否存在
var xmlObj = false;
function DownloadPng() {
//判断是否是IE浏览器
if (window.ActiveXObject) {
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlObj = new XMLHttpRequest();
}
xmlObj.open('GET', 'PngInfo.xml', true);
//使用异步方式所以要在XMLHttpRequest对象的状态改变时做相应的处理
xmlObj.onreadystatechange = function () {
//判断XMLHttpRequest的状态,如果是4 ,继续处理
if (xmlObj.readyState == 4) {
//需要判断返回状态时否是200
if (xmlObj.status == 200) {
DoXml();
}
}
}
//发送请求,因为是GET,所以send的内容是null
xmlObj.send(null);
function DoXml() {
var xmlDoc = xmlObj.responseXML;
var imageName = xmlDoc.getElementsByTagName("location")[0].childNodes[0].nodeValue;
console.log(imageName);
var location = "file/" + imageName + ".png";
xmlObj.open("Get", location , true);
xmlObj.send();
if (xmlObj.status == 404) {
console("图片不存在");
} else {
console("图片存在");
}
}
访问的html 后缀待参数,读取参数作为文件名
例如 http://10.0.xx.xxx:8090/download.html?imagename=sssxx01
var ImageName = ""; urlinfo = window.location.href; //获取当前页面的 len = urlinfo.length;//获取url的长度 offset = urlinfo.indexOf("?");//设置参数字符串开始的位置 if (offset == -1) { ImageName = "不存在"; } else { newsidinfo = urlinfo.substr(offset, len)//取出参数字符串 这里会获得类似“id=1”这样的字符串 newsids = newsidinfo.split("=");//对获得的参数字符串按照“=”进行分割 newsid=newsids[1]; ImageName = newsids[1]; }
记录和分享用过的技术、基础、方法