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

登陸以後的請求會帶登陸用戶信息,須要把登陸時的cookie設置到以後的請求頭裏面。而跨域請求要想帶上cookie,必需要在vue的main.js里加上axios.defaults.withCredentials = true。withCredentials 屬性是一個Boolean類型,它指示了是否該使用相似cookies,authorization,headers(頭部受權)或者TLS客戶端證書這一類資格證書來建立一個跨站點訪問控制(cross-site Access-Control)請求。javascript

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不能是*。
vue

相關文章
相關標籤/搜索