本文介绍了在 Spring Boot 中全局启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试像这样全局启用 CORS:
I tried to enable CORS globally like this:
@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.
An annotation @CrossOrigin for an individual class works, but I wanted to enable CORS it globally.
推荐答案正如您在回答中提到的那样,您确实可以定义自己的 Filter.Spring已经有了这样的CorsFilter 已经,所以你不必自己创建一个.只需将其注册为 bean 就可以了:
You could indeed define your own Filter as you mentioned in your answer. Spring already has such a CorsFilter already though, so you don't have to create one yourself. Just register it as a bean and it should work:
@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); }更多推荐
在 Spring Boot 中全局启用 CORS
发布评论