首先看一下原始代码:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://47.99.63.22/vue");
corsConfiguration.addAllowedOrigin("http://47.99.63.22/lab");
corsConfiguration.addAllowedOrigin("http://47.99.63.22:8096/schedule/all");
corsConfiguration.addAllowedOrigin("http://47.99.63.22:8096/*");
corsConfiguration.addAllowedOrigin("http://localhost:5173");
corsConfiguration.addAllowedOrigin("http://localhost:5174");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration);
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source);
}
可能存在以下问题:
1、不正确的allowedOrigins配置
2、精确的源而不是通配符
3、注册的顺序和实例化
修正上述问题后的示例代码可能如下所示:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://47.99.63.22"); // 注意这里去掉了路径和通配符
corsConfiguration.addAllowedOrigin("http://localhost:5173");
corsConfiguration.addAllowedOrigin("http://localhost:5174");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
确保增加MAX_AGE的定义(如果尚未定义),它应该是一个时间长的长整数值,例如:
private static final long MAX_AGE = 24 * 60 * 60;
这里主要的问题在于,addAllowedOrigin方法应该只包含协议、域名和端口,不能指定路径。