千古难遇,跨域CORSConfig不生效的问题

我在其他模块配置的跨域生效,到了这里就不生效了,弄来弄去,原来是文件名称的问题,估计是springboot底层配置了相应的bean有名称为CORSConfig

1.我的跨域配置

@Configuration
public class CORSConfig {
    
    
    private CorsConfiguration buildConfig() {
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");                // 设置访问源请求头
        corsConfiguration.addAllowedMethod("GET");              // 允许GET方法访问
        corsConfiguration.addAllowedMethod("POST");             // 允许POST方法访问
        corsConfiguration.addAllowedMethod("OPTIONS");          // 允许OPTIONS方法访问
        corsConfiguration.setAllowCredentials(Boolean.TRUE);
        // 2.4以后这样设置 替换 addAllowedOrigin("*)
        corsConfiguration.setAllowedOriginPatterns(Arrays.asList(CorsConfiguration.ALL));
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }

}

2.异常原因

把文件名CORSConfig改成其他名字就好了,比如 PASSCORSConfig,
ACORSConfig,

3.总结

名字叫CORSConfig / GlobalCORSConfig 跨域文件有时候会出问题

4.正常的config

package cn.wisegraph.purchasems.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class PassCorsConfig {
    
    
    private CorsConfiguration buildConfig() {
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");                // 设置访问源请求头
        corsConfiguration.addAllowedMethod("GET");              // 允许GET方法访问
        corsConfiguration.addAllowedMethod("POST");             // 允许POST方法访问
        corsConfiguration.addAllowedMethod("OPTIONS");          // 允许OPTIONS方法访问
        corsConfiguration.setAllowCredentials(Boolean.TRUE);
        // 2.4以后这样设置 替换 addAllowedOrigin("*)
        corsConfiguration.setAllowedOriginPatterns(Arrays.asList(CorsConfiguration.ALL));
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_42581660/article/details/127789477