其他分享
首页 > 其他分享> > SpringBoot 配置跨域异常

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("*");
    }
}

标签:SpringBoot,allowCredentials,registry,跨域,异常,public,allowedOrigins
来源: https://www.cnblogs.com/zym-k/p/15862181.html