问题描述:
在学习谷粒商城时遇到了Cors错误,点击登陆出现500错误。
根据提供的日志,错误信息指出了问题的原因和解决方法:
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.
这个错误说明,当allowCredentials
设置为true
时,allowedOrigins
不能包含特殊值*
,因为它不能设置在 "Access-Control-Allow-Origin" 响应头中。要允许凭证到一组来源,应该明确列出它们,或者考虑使用 allowedOriginPatterns
。
原有的代码为:
@Configuration
public class MyCoresConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1.配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
解决这个问题的方法是修改你的CORS配置,将 allowedOrigins
中的 *
替换为具体的允许的来源,或者使用 allowedOriginPatterns
来指定允许的来源的模式。例如,如果你想允许所有来源,可以这样配置:
问题在于allowedOrigins
设置为 *
时,不允许设置 allowCredentials
为 true
。为了解决这个问题,可以使用 allowedOriginPatterns
来代替 allowedOrigins
,因为allowedOriginPatterns
支持允许所有来源的情况,并允许 allowCredentials
设置为 true
。
修改后的代码:
@Configuration
public class MyCoresConfiguration {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
// 使用 allowedOriginPatterns 代替 allowedOrigins
corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(source);
}
}
修改后响应成功: