記前端跨域請求踩坑記


今天在做Springboot +vue+axios時發送了跨域請求發現報記前端跨域踩坑,報Access to XMLHttpRequest at 'http://localhost:7050/runtime/uav/bookmark/photo/1' from origin 'http://192.168.1.112:8816' 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.

 

翻譯: 當請求憑證模式為“include”時,Access-Control-Allow-Origin這個響應頭設置不能為通配符“*”,憑證模式通過XMLHttpRequest 對像的withCredentials 屬性初始化。

 

 題外:withCredentials是xhr對象的一個屬性。它的值是boolean。若為true,則執行跨域請求時在請求頭中挾帶憑據信息。否則不挾帶。憑據信息包括cookie、http認證、客戶端ssl……。常用cookie為憑據。
           axios是基於(但不限於)xhr+promise做出來的。axios也有withCredentials屬性。

 

原因:發送的是帶有憑證的請求,但服務器沒有包含這個頭部,所以被瀏覽器攔截,所以在傳傳Cookie等務端的Access-Control-Allow-Origin必須配置具體的域名。

 

使用帶有憑證的場景:開發環境,並且需要用到登錄額cookie的

 

 

解決的方法:

1后端解決:

    1-1在后端的過濾器中設置請求頭為具體的站點不用通配符,response.setHeader("Access-Control-Allow-Origin", "允許訪問的站點");

     1-2(推薦),在后端的過濾器中設置請求頭為自動獲取當前請求的站點,response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

2.前端解決

     檢查Axsios的配置,把http://Axios.defaults.withCredentials = true注釋掉

 


免責聲明!

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



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