报错信息:当allowCredentials为true时,allowedOrigins不能包含特殊值“*”,因为它不能在“Access-Control-Allow-Origin”响应头中设置。要允许凭据到一组来源,请显式列出它们,或者考虑使用“allowedOriginPatterns”。

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.

java跨域完整代码:

//在后端启动文件同级目录,创建一个目录Corsconfig
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //设置属性
        //允许跨域请求的地址,*表示所以
//      corsConfiguration.addAllowedOrigin("*");//注意:这个注释,换成下面一行的代码
        corsConfiguration.addAllowedOriginPattern("*");
        //跨域的请求头
        corsConfiguration.addAllowedHeader("*");
        //跨域的请求方法
        corsConfiguration.addAllowedMethod("*");
        //在跨域请求的时候使用同一个Session
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",buildConfig());
        return new CorsFilter(source);
    }

}

上面是完整的跨域代码:

其实导致跨域问题的原因是:corsConfiguration.addAllowedOrigin("*");

换成corsConfiguration.addAllowedOriginPattern("*");就可以了。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐