SpringBoot 配置跨域异常

SpringBoot 配置跨域异常:java.lang.IllegalArgumentException

1. 问题描述:

SpringBoot 配置跨域时出现如下异常:

java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

2. 问题原因:

SpringBoot升级2.4.0+之后,跨域配置中的.allowedOrigins不再可用

3. 解决办法:

将配置中的.allowedOrigins替换成.allowedOriginPatterns即可。

4. 不同版本配置对比:

SpringBoot 2.0.0<=version<2.4.0

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

SpringBoot >= 2.4.0

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}
上一篇:Java基础学习补充 -- 异常处理和log4j日志


下一篇:无阻塞加载和defer、async