前后端分离的项目,使用Ajax请求一般都出现跨域的问题。
跨域的时候所创建的session是不会被浏览器保存下来的。所以每次进行跨域请求时,服务器都认为不是同一个浏览器所发起的请求,session也会不一样。以下将介绍如何保证session一致。
前端Ajax请求
$.ajax({
url:url,
<! -- 加上此部分 Start-- >
xhrFields: {
withCredentials: true
},
crossDomain: true,
<! -- 加上此部分 End-- >
success:function() {
},
error:function() {
}
});
后端构建一个拦截器,对需要跨域访问的request头部重写
如:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response= (HttpServletResponse) servletResponse;
HttpServletRequest request=(HttpServletRequest)servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("XDomainRequestAllowed","1");
filterChain.doFilter(servletRequest,servletResponse);
}
另外Spring boot的项目可以添加拦截配置,以下:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AuthCorsFilter extends CorsFilter {
public AuthCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}