java+vue跨域每次请求获取不同session问题

描述

vue在做登录的时候,明明已经把用户数据存入了httpsession中,但在后面的请求拦截中发现获取的session属性size为0

断点发现登录用的session和拦截得到的session不是一个id,也就是说不是同一个session

查资源得到解决办法

java端

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {
     

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
     
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.addHeader("Access-Control-Allow-Credentials", "true");
        //允许前端跨域携带cookie   axios.defaults.withCredentials = true;
        resp.addHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
        resp.addHeader("Access-Control-Allow-Methods", "*");
        resp.addHeader("Access-Control-Allow-Headers", "Content-Type,token");
        //前端ajax请求OPTIONS直接放行,解决不能得到header里token问题
        if (req.getMethod().equals("OPTIONS")) {
     
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
     
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
     
    }
}

vue端

axios.defaults.withCredentials = true;// 允许跨域携带cookie

你可能感兴趣的:(前端笔记,java笔记本,session,cookie)