下载的时候报错:Access to XMLHttpRequest at 'http://127.0.0.1:10667/admin/sys/generator/code' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
1、刚遇到这个问题的时候,还以为是后端原因,一直捣鼓后台,百度学习了解,发现不是后端问题,,,,,此时脑细胞不够用。。
2、休息一会,开足马力,很老土的查找方式,那就是翻译报错的句子,如下:
前面一直针对 响应中“ Access-Control-Allow-Origin”标头的值不得为通配符“ *” 进行分析,翻译出来后,发现 XMLHttpRequest 这玩意也参与阻止,于是根据 XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制 进行查找,最后是发现是同事搭建项目的时候配置了这个:
于是 我将它改为
完美解决前端显示跨域问题。
(一) 当前端配置withCredentials=true
时, 后端配置Access-Control-Allow-Origin
不能为*
, 必须是相应地址
(二) 当配置withCredentials=true
时, 后端需配置Access-Control-Allow-Credentials
(三) 当前端配置请求头时, 后端需要配置Access-Control-Allow-Headers
为对应的请求头集合
// 封装下载请求的方式 ,来源于 api.js
function download(url, params) {
let loadUrl = BASE_URL + url;
return axios.post(loadUrl, params, { responseType:'blob' });
}
// 具体的业务请求
handleSubmit(formName){
if (!this.selectTable) {
return;
}
this.generatorForm.tables = this.selectTable;
let params = this.generatorForm;
this.$refs[formName].validate((valid) => {
if (valid) {
this.api.generatorCode(params).then(response =>{
if (response === 'undefined'){
return;
}
console.log("response====",response);
let url = window.URL.createObjectURL(new Blob([response.data]));
let link= document.createElement('a');
link.style.display='none';
link.href=url;
link.setAttribute('download', 'source-code.zip');
document.body.appendChild(link);
link.click();
});
}
});
},
设置响应体,如 HttpServletResponse response :
response.setHeader("Access-Control-Allow-Origin","*");
基于springboot开发,在contronler上加上:@CrossOrigin
本文只想表述的是在遇到问题的时候,不一定根据首要错误码查找线索,有时候倒数那几句 话,也会让你产生怦然心动。
涉及的技术:axios 、http跨域、后端跨域
学习的文章:https://juejin.im/post/5c2490ba6fb9a049ff4e2eca