SpirngBoot项目解决前后端联调的跨域和存cookie问题
1.处理背景
在做vue+springboot的项目中,配置自己的axios需要使用cookie存用户的登录态。
在实现的axios中添加:
myAxios.defaults.withCredentials = true; //携带cookie
但是在之前没有问题的前提下,出现了如下问题
Access to XMLHttpRequest at 'http://localhost' 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-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
2. 解决方案
尝试一:
在自实现的axios中添加下方配置
myAxios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
未能解决。(解决后删除这行配置不影响)
尝试二:
参考了https://blog.csdn.net/ww_ndsc_ww/article/details/113175746博客后了解到:CORS请求默认不发送Cookie和HTTP认证信息。如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow-Credentials字段。
参考了https://juejin.cn/post/6844903748288905224,在后端配置SimpleCORSFilter继承Filter方法。
增加下方配置
response.setHeader("Access-Control-Allow-Credentials", "true");
3.总结:解决跨域问题和传Cookie问题
解决跨域:在Controller类中配置下方注解(springboot2.7没有配置 Access-Control-Allow-Credentials为true)
@CrossOrigin(origins = {"http://localhost:5173"})
解决跨域并且可传cookie:配置自己的过滤器,并注入到spring容器中(同步解决了可能出现的预处理不通过问题)
@Component
@Slf4j
public class SimpleCORSFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//log.error("我被注入啦!");
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");//不可以传*
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
response.setHeader("Access-Control-Allow-Credentials", "true");//这行是关键
HttpServletRequest request = (HttpServletRequest)req;
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);.//解决预处理
return;
}
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}

浙公网安备 33010602011771号