本文介绍了在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.
推荐答案您确实可以定义自己的过滤器回答。 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
发布评论