1.引言
作者在进行联系session分布式登录的时候,遇到了一个问题,就是明明我的后端进行配置了允许跨域,但是前端依然请求失败,无法收到请求,并报出如下错误。
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
2.问题引入
2.1前端的axios的配置
由于需要进行使用cookie等请求凭证相关的东西,在默认情况下,axios进行发送请求到后端的时候是不提供请求凭证的(cookie、HTTP认证及客户端SSL证明等),所以需要进行设置axios.defaults.withCredentials = true
2.2后端配置跨域
由于后端是为了保证安全的,前端配置跨域可能是一种曲线救国的方案,所以我选择了使用后端进行配置解决跨域,由于目前暂时无需进行考虑到线上环境安全问题,我使用了最为朴素的方式进行配置跨域。
2.3出现问题
但是正因为此就出现了问题,我的前端直接请求不过去了,我发现请求码是200并不是403,说明并没有因为跨域问题后端给我拦截下来啊,明显我的请求已经被后端接收了,并且我通过对后端代码进行DeBug后发现,接口整体是完全跑通了,但是为什么前端没有接收到后端返回的数据呢?
3.解决问题
3.1前端请求的小知识
当前端进行设置请求发送cookie等凭证的时候,需要后端的响应头response进行设置Access-Control-Allow-Origin,并且不能为*,必须进行绑定域名,告诉前端能不能展示后端返回的数据,否则就会报错跨域问题,所以我们需要给每个接口的response设置Access-Control-Allow-Origin=域名。
3.2问题解决
3.2.1使用原始办法解决
每个接口都进行这样配置
3.2.2使用Filter过滤器进行统一配置解决
@WebFilter(filterName = "CorsFilter") @Configuration public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); chain.doFilter(req, res); } }
还没有评论,来说两句吧...