基於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();
                  });
                    }
                });
            },

四、其他

   本文只想表述的是在遇到問題的時候,不一定根據首要錯誤碼查找線索,有時候倒數那幾句 話,也會讓你產生怦然心動。

   涉及的技術:axios 、http跨域、後端跨域

   學習的文章:https://juejin.im/post/5c2490ba6fb9a049ff4e2eca

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章