vue中使用axios 遇到post 跨與問題解決-qs的使用


在vue項目中常常會使用axios進行后端交互,如果使用get一般沒問題,但是使用post發送請求時會出現跨與報錯。

Access to XMLHttpRequest at 'http://192.168.6.199/pushDD_request_tz.php' from origin 'your url' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

這時候我們需要引入第三方模塊幫我們解決這個問題:

1:安裝qs : npm install qs

2:引入:import qs from  qs

3:使用:

axios.post('http://192.168.33.10:8009/api/token',
qs.stringify({
email: email,
password: pass,
}))
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);

});

 

代碼:

 this.$http({
              method:'post',
              url:url,
              scriptCharset:"utf8",
              data:qs.stringify({    //這里是發送給后台的數據
                username:this.ajaxName,
                uid:record.uid,
                tz_name:tuzi.filename,
                tz_url:tuzi.file_url,
                tz_parent:tuzi.parent,
                tz_status:tuzi.status,
              })
              // data:{    //這里是發送給后台的數據 不用qs的話會出現跨與報錯
              //                 username:this.ajaxName,
              //                 uid:record.uid,
              //                 tz_name:tuzi.filename,
              //                 tz_url:tuzi.file_url,
              //                 tz_parent:tuzi.parent,
              //                 tz_status:tuzi.status,
              // }
              }).then((res) =>{//這里使用了ES6的語法
                  // if(res.data!==1) return
                  console.log(res)
                  // window.open(url)//下載
              }).catch((error) =>{
                  console.log(error)       //請求失敗返回的數據
              })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM