后端添加如下代码
package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * 请求的基本过滤器 预处理请求头 */ @WebFilter(urlPatterns = {"/*"}, filterName = "tokenAuthorFilter") public class TokenAuthorFilter implements Filter { private static Logger LOG = LoggerFactory.getLogger(TokenAuthorFilter.class); @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse rep = (HttpServletResponse) response; HttpSession session = req.getSession(); rep.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); rep.setHeader("Access-Control-Allow-Credentials", "true"); rep.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH"); rep.setHeader("Access-Control-Max-Age", "0"); rep.setHeader("Access-Control-Allow-Headers", "token, Origin, X-Requested-With, Content-Type, Accept"); //谷歌浏览器需要以下设置才能保证下一次请求会携带cookie if(rep.getHeader("Set-Cookie") != null){ rep.setHeader("Set-Cookie",rep.getHeader("Set-Cookie")+"; Secure=true; Samesite=none"); } chain.doFilter(req, rep); } @Override public void init(FilterConfig arg0) throws ServletException { } }
前端添加配置
axios.defaults.withCredentials=true;