vue+Java 前后端分离,多次请求Session不一致的问题
Vue项目用的axios发送请求
在main.js中增加以下配置:
import axios from 'axios'; axios.defaults.withCredentials=true;
使用时,设置withCredentials: true(请求时携带凭证信息)
axios({ url: url, data: data, headers: { 'Content-Type': 'multipart/form-data' }, method: 'POST', withCredentials: true }).then(response => { resolve(response) }
服务端添加filter
private final List<String> allowedOrigins = Arrays.asList("http://localhost:8089","http://localhost:8088");// 允许跨域的地址 @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; response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type"); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", allowedOrigins.contains(origin) ? origin : ""); // 是否允许浏览器携带用户身份信息(cookie) response.setHeader("Access-Control-Allow-Credentials","true"); // 图片上传会用到 if( "OPTIONS".equals(request.getMethod())){ } filterChain.doFilter(servletRequest, servletResponse); }
方法中有一行if( "OPTIONS".equals(request.getMethod()))
的判断,是因为我在做图片上传时,登录认证会失效导致跳转到登录页。
后来发现原因是在做图片上传时,会在POST请求之前,先发送一个OPTION的预请求,这个请求的作用主要是 获取服务器支持的HTTP请求方法,用来检查服务器的性能或判断后续请求是否安全。。
如果是OPTIONS请求,不会执行filterChain.doFilter(servletRequest, servletResponse),以至于之后的shiro校验不生效,所以会没有权限。
相关推荐
jxiao000 2020-09-29
zjutzmh 2020-09-25
ApeLife技术 2020-07-04
ApeLife技术 2020-06-26
Ken专注后端技术 2020-05-28
nullcy 2020-05-26
SAMXIE 2020-05-12
jxiao000 2020-05-04
hzyuhz 2020-05-04
林大夏 2020-03-27
jxiao000 2020-02-20
bowean 2020-02-19
shuiluobu 2020-01-29
Ken专注后端技术 2020-01-29
ChinaGuanq 2020-01-19
xxuncle 2020-01-17
Julywhj 2019-12-27