Spring boot Cors跨域异常:When allowCredentials is true, allowedOrigins cannot contain the special value

Spring boot Cors跨域异常:When allowCredentials is true, allowedOrigins cannot contain the special value

码农世界 2024-06-14 后端 103 次浏览 0个评论

When allowCredentials is true, allowedOrigins cannot contain thespecial 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.

问题:

       出现该问题是跨域问题,当allowCredentials为true时,allowingOrigins不能包含特殊值“ *”,因为无法在“ Access-Control-Allow-Origin”响应标头上设置。 

解决:

       将allowingOrigins换成allowedOriginPatterns即可。

 修改前:

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

修改后:

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

其它解决跨域方式

    可使用Spring 注解@CrossOrigin,可以直接在Controller顶部加入即可如下图:

Spring boot Cors跨域异常:When allowCredentials is true, allowedOrigins cannot contain the special value

转载请注明来自码农世界,本文标题:《Spring boot Cors跨域异常:When allowCredentials is true, allowedOrigins cannot contain the special value》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,103人围观)参与讨论

还没有评论,来说两句吧...

Top