異常:
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.
原因:Springboot版本高於2.4.0 才會出現這樣的問題,再結合報錯信息提示不能使用*號設置允許的Origin
,所以有兩個解決方法。
解決方法1:
降低SpringBoot版本。在pom.xml中修改springboot版本值,並刷新
<modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
解決方法2:
如果不降低版本,則在跨域設置時使用setAllowedOriginPatterns
方法。(親測有效)
修改前:
/** * 跨域配置 */ @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); // 是否允許請求帶有驗證信息 config.setAllowCredentials(true); // 設置訪問源地址 config.addAllowedOrigin("*"); // 設置訪問源請求頭 config.addAllowedHeader("*"); // 設置訪問源請求方法 config.addAllowedMethod("*"); // 對接口配置跨域設置 source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }
修改后:
/** * 跨域配置 */ @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); // 是否允許請求帶有驗證信息 config.setAllowCredentials(true); // 允許訪問的客戶端域名 // (springboot2.4以上的加入這一段可解決 allowedOrigins cannot contain the special value "*"問題) List<String> allowedOriginPatterns = new ArrayList<>(); allowedOriginPatterns.add("*"); config.setAllowedOriginPatterns(allowedOriginPatterns); // 設置訪問源地址 // config.addAllowedOrigin("*"); // 設置訪問源請求頭 config.addAllowedHeader("*"); // 設置訪問源請求方法 config.addAllowedMethod("*"); // 對接口配置跨域設置 source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }