我试图像这样在全球范围内启用CORS:
@Configuration @ComponentScan("com.example") @EnableWebMvc public class OriginFilter extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE"); } }
我也尝试过这种方法:
@Configuration public class OriginFilter implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD") .allowCredentials(true); } }
但是这些都不对我有用。
可以@CrossOrigin为单个类添加注释,但是我想在全局范围内启用CORS。
@CrossOrigin
您确实可以Filter按照答案中的定义定义自己的名称。Spring已经有了这样的功能CorsFilter,因此您不必自己创建一个。只需将其注册为bean,它就可以工作:
Filter
CorsFilter
@Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // Don't do this in production, use a proper list of allowed origins config.setAllowedOrigins(Collections.singletonList("*")); config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept")); config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }