springMvc跨域
1. Spring框架还提供了CorsFilter
在这种情况下,不用使用@CrossOrigin或WebMvcConfigurer#addCorsMappings(CorsRegistry),可以在Spring Boot应用程序中声明如下的过滤器:
@Configuration public class MyConfiguration { @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://domain1.com"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; } }
2. 全局CORS配置
如果您正在使用Spring Boot,建议将WebMvcConfigurer bean声明如下:
@Configuration public class MyConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } }; } }
3.
/** * WebMvc配置 */ @Configuration public class WebConfig implements WebMvcConfigurer { //跨域解决 static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" }; @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS) .maxAge(3600); } }