在 Spring Boot 中全局启用 CORS

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

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

发布评论

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

>www.elefans.com

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