歡迎訪問抒穎家查看更多信息
詳細錯誤信息 Access to XMLHttpRequest at 'http://localhost:7894/Login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
前端 vue-antd-admin
后端 java servlet
前后端分離的項目中肯定會碰到跨域的問題,跨域的原因還是為了安全。最近在做一個項目的時候發現,即使我已經設置了跨域信息,前端還是報這個跨域錯誤。
后來找了有經驗的后台來幫忙也是弄了很久都沒有解決問題,后來我慢慢看請求頭和仔細尋找前后端的代碼終於發現了端倪。
我項目中失敗的請求頭
參考自MDN中失敗的一個請求頭
可以發現多了Authorization
和Accept
兩個請求頭,這兩個請求頭來自前端項目中的src/utils/request.js
對請求經行了簡單的安全設置,使得請求中攜帶了安全信息,查看源代碼發現代碼中設置了
axios.defaults.withCredentials= true
表示客戶端想要攜帶驗證信息,這部分功能需要后台支持,而后台supportsCredentials
一般被設置為false
即不支持客戶端攜帶驗證信息
對后台代碼進行修改
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
res.addHeader("Access-Control-Allow-Methods", "*");
res.addHeader("Access-Control-Allow-Headers", "Accept,Authorization,DNT,Content-Type,Referer,User-Agent");
res.addHeader("Access-Control-Allow-Credentials","true"); // 允許攜帶驗證信息
chain.doFilter(req, res);
}
問題解決