因为项目后端是重写了WebMvcConfigurer,然后添加的跨域请求。添加拦截器之后,根据token信息返回状态响应码并且preHandle返回的是false。熟悉拦截器的可知,preHandle返回false后会终止请求,也就是说后面配置的跨域方法不起作用了,这也就造成了前端的跨域问题。所以需要在拦截器中配置跨域请求才能解决。
代码如下:
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//从http请求头中取出token
String token = request.getHeader("Authorization");
//如果不是方法级别的请求,则直接通过
if (!(handler instanceof HandlerMethod)){
return true;
}
//利用java反射获取到请求的方法
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
//如果方法添加了LoginToken注解
if(method.isAnnotationPresent(LoginToken.class)){
LoginToken loginToken = method.getAnnotation(LoginToken.class);
if (lo