解决Access-Control-Allow-Origin跨域问题
方法五与前四种的区别:浏览器一般发两次请求,一次OPTIONS的,一次正式的,如果OPTIONS请求不能取到token,会报下面错误:
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
解决方法就是OPTION请求时不校验token。
注:方法五与前四种属于不同类型,并不是前四种的替代方式。方法五一定要考虑
方法一:给response设置header
public User getUser(HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin","*"); User user = new User(1,"张三",20); return user; }
方法二:添加注解,如果添加到类上,那么整个类中的方法都可以跨域访问
@CrossOrigin public User getUser2(HttpServletResponse response) { User user = new User(2,"李四",20); return user; }
方法三:在拦截器中设置response的header,以下是springboot中的写法
public class WebInterceptor implements HandlerInterceptor{
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.setHeader("Access-Control-Allow-Origin","*"); return true; } }
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new WebInterceptor()); } }
方法四:实现WebMvcConfigurer接口,重写addCorsMappings方法,如下:
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer{ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET","POST","PUT","DELETE","HEAD"); } }
方法五:继承shiro的AuthenticationFilter,重新isAccessAllowed方法,如下:
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { HttpServletRequest httpServletRequest = (HttpServletRequest)request; String method = httpServletRequest.getMethod().toUpperCase(); //OPTIONS请求直接放过,不需要校验token,避免报OPTIONS预请求跨域错误 if("OPTIONS".equals(method)){ return true; } return super.isAccessAllowed(request, response, mappedValue); }