Springboot跨域问题三种解决方案
1.自定义跨域过滤器
编写过滤器
public class MyCorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; //是否允许后续请求携带认证信息(cookies),该值只能是true,否则不返回 res.addHeader("Access-Control-Allow-Credentials", "true"); //指定允许其他域名访问 // 一般用法(*,指定域,动态设置),3是因为*不允许携带认证头和cookies res.addHeader("Access-Control-Allow-Origin", "*"); //该次请求的请求方式 res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); //该次请求的自定义请求头字段 res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN"); if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) { response.getWriter().println("ok"); return; } chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
注册过滤器
/** * 注册自定义跨域过滤器 */ @Bean public FilterRegistrationBean registerFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.addUrlPatterns("/*"); bean.setFilter(new MyCorsFilter()); return bean; }
2.针对单个接口,使用注解@CrossOrigin
@CrossOrigin @RequestMapping("customAnalysisConfig") @RestController public class CustomAnalysisConfigController {
}
3.基于WebMvcConfigurerAdapter配置加入Cors的跨域
@Configuration public class CorsConfig implements WebMvcConfigurer { /** * 跨域支持 */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(3600); } }