解决前后端分离开发sessionId不一致问题
在做一个前后分离项目时,发现登录成功后已经把信息保存到session中了,再从session中获取当前用户信息的时候发现取不到,debug发现sessionId已经发生改变,最近在网站查找很多,但是并没有解决什么问题所以
把自己的解决的方式分享给大家:
**
后端拦截器:
**
//拦截器添加跨域支持(如果使用web.xml配置拦截器,请将@component删除)
//@Component
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("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"); //是否支持cookie跨域
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
关键点:
response.setHeader(“Access-Control-Allow-Origin”, request.getHeader(“Origin”));
response.setHeader(“Access-Control-Allow-Credentials”,“true”); //是否支持cookie跨域
前段代码:
request: function(param) {
var _this = this;
$.ajax({
xhrFields: {
withCredentials: true
},
type: param.method || ‘get’,
url: param.url || ‘’,
dataType: param.type || ‘json’,
data: param.data || ‘’,
success: function(res) {
console.log(“网络请求结果:”+res.toString());
//请求成功
},
error: function(err) {
typeof param.error === 'function' && param.error(err.statusText);
}
});
},
关键点:
在ajax请求中增加
xhrFields: {
withCredentials: true
},
经过上面的配置,完美的解决了我的问题!如果有疑问可以给我留言。