axios.defaults.withCredentials = true 前端跨域設定

2020-10-13 03:00:17

登入之後的請求會帶登入使用者資訊,需要把登入時的cookie設定到之後的請求頭裡面。而跨域請求要想帶上cookie,必須要在vue的main.js里加上axios.defaults.withCredentials = true。withCredentials 屬性是一個Boolean型別,它指示了是否該使用類似cookies,authorization,headers(頭部授權)或者TLS使用者端證書這一類資格證書來建立一個跨站點存取控制(cross-site Access-Control)請求。

axios.defaults.withCredentials = true;//設定cross跨域 並設定存取許可權 允許跨域攜帶cookie資訊

但是前端這樣設定之後發現報錯了!

Access to XMLHttpRequest at '...' from origin '...' 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.

原因是:前端設定withCredentials的情況下,後端要設定Access-Control-Allow-Origin為你的源地址,例如http://localhost:8080,不能是*,而且還要設定header(‘Access-Control-Allow-Credentials: true’);
另外,Access-Control-Allow-Origin設定為*,時cookie不會出現在http的請求頭裡,所以報錯裡說Access-Control-Allow-Origin不能是*。