浏览器报`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'. `问题的解决方案

欢迎访问moshuying.top查看更多信息

详细错误信息 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

前后端分离的项目中肯定会碰到跨域的问题,跨域的原因还是为了安全。最近在做一个项目的时候发现,即使我已经设置了跨域信息,前端还是报这个跨域错误。

后来找了有经验的后台来帮忙也是弄了很久都没有解决问题,后来我慢慢看请求头和仔细寻找前后端的代码终于发现了端倪。

我项目中失败的请求头

DkcrSU.png

参考自MDN中失败的一个请求头

img

可以发现多了AuthorizationAccept两个请求头,这两个请求头来自前端项目中的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);
}

问题解决

参考链接

mozilla的HTTP访问控制
介绍了跨域中其他的头信息

原文地址:https://www.cnblogs.com/moshuying/p/13984508.html