前后端分离获取不到session问题
前后端分离的项目,前端是vue,后端springboot,或者maven项目,生成验证码的时候存了一份到session并存到redis里,前端调后台注册获取不到session,但当用户从session中取信息的时候发现始终取不到,每次跨域请求时ajax发送的都是新的sessionid,导致无法获取信息解决方案:前端在vue的main文件全局添加一下代码:import axios from '...
·
前后端分离的项目,前端是vue,后端springboot,或者maven项目,生成验证码的时候存了一份到session并存到redis里,前端调后台注册获取不到session,但当用户从session中取信息的时候发现始终取不到,每次跨域请求时ajax发送的都是新的sessionid,导致无法获取信息
解决方案:
前端在vue的main文件全局添加一下代码:
import axios from 'axios';
axios.defaults.withCredentials=true;
后台新增一个过滤器
web.xml文件
<filter>
<filter-name>contextFilter</filter-name>
<filter-class>com.zl.filter.ContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>contextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
public class ContextFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpServletRequest request = (HttpServletRequest)servletRequest;
String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "*");
String headers = request.getHeader("Access-Control-Request-Headers");
// 支持所有自定义头
if (!org.springframework.util.StringUtils.isEmpty(headers)) {
response.setHeader("Access-Control-Allow-Headers", headers);
}
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600");
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)