前后端分离项目,支持跨域,session不丢失

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/woshiyeguiren/article/details/79194003

    在调试一个前后端分离的项目,发现登录成功后已经把信息保存到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
       },

经过上面的配置,完美的解决了我的问题!如果有疑问可以给我留言。







没有更多推荐了,返回首页