在Spring Boot中全局启用CORS

编程入门 行业动态 更新时间:2024-10-11 01:17:28
本文介绍了在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

本文发布于:2023-10-30 04:52:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   Spring   Boot   CORS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!