Spring Boot 升级后 原有版本无法使用 原版如下:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
这个方式会报错
报错内容如下:
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.
网上关于解决此方式如下:
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1,允许任何来源
corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
//2,允许任何请求头
corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
//3,允许任何方法
corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
//4,允许凭证
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
但我实际运行发现 代码在最后一行编辑器报错 研究发现是无法转换 内容如下:
java: 不兼容的类型: org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource无法转换为org.springframework.web.cors.CorsConfigurationSource
研究发现UrlBasedCorsConfigurationSource是转换不了CorsFilter的 CorsFilter是个类 UrlBasedCorsConfigurationSource 是实现了CorsConfigurationSource接口 且这个接口是顶级接口 转换不了 编辑器报错 强转编译器也会报错
所以我实在不知道为什么这个方式还好多人评论可行的
我研究了官网发现如下示例
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true).maxAge(3600);
// Add more mappings...
}
}
但是官网的还是会报文章开头的错误 难道官网的有问题?应该不会 我继续查找发现这个链接可以有效解决
最终解决方案如下:
@Component
public class WebConfig implements WebMvcConfigurer {
private static final Logger logger = LogManager.getLogger(WebConfig.class);
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOriginPatterns("*")
// 设置允许的方法
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
// 是否允许证书(cookies)
.allowCredentials(true)
// 跨域允许时间
.maxAge(3600);
}
}