基于vue开发的前端跨域问题Access-Control-Allow-Origin

一、报错提示

   下载的时候报错: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属性控制 进行查找,最后是发现是同事搭建项目的时候配置了这个:

  axios.defaults.withCredentials = true;

于是 我将它改为  

 axios.defaults.withCredentials = false;

完美解决前端显示跨域问题。

注意:

(一) 当前端配置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

猜你喜欢

转载自blog.csdn.net/baidu_28068985/article/details/105558280
今日推荐