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校验不生效,所以会没有权限。