springboot2.5以上版本
    参考地址:https://www.cnblogs.com/youcong/p/13583743.html

    1. import org.springframework.context.annotation.Bean;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.web.cors.CorsConfiguration;
    4. import org.springframework.web.cors.reactive.CorsWebFilter;
    5. import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
    6. import org.springframework.web.util.pattern.PathPatternParser;
    7. @Configuration
    8. public class CorsConfig {
    9. @Bean
    10. public CorsWebFilter corsFilter() {
    11. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    12. source.registerCorsConfiguration("/**", buildConfig());
    13. return new CorsWebFilter(source);
    14. }
    15. private CorsConfiguration buildConfig() {
    16. CorsConfiguration corsConfiguration = new CorsConfiguration();
    17. //在生产环境上最好指定域名,以免产生跨域安全问题
    18. corsConfiguration.addAllowedOrigin("*");
    19. corsConfiguration.addAllowedHeader("*");
    20. corsConfiguration.addAllowedMethod("*");
    21. return corsConfiguration;
    22. }
    23. }