我在 spring 项目中工作,我希望允许多个来源调用我的后端 API。到目前为止,我的配置仅适用于一个来源。这是我的代码:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("myoriginone");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
你知道我如何允许多个来源吗?类似于 "host1","host2".. 因为 addAllowedOriginPattern() 方法只接受一个字符串参数。
问候。
回答1
如果您查看文档,则 allowedOrigins
是一个数组。
@Nullable
private List<String> allowedOrigins;
以下方法是设置允许的来源。显然,您可以多次调用该方法来添加不同的来源。
/**
* Add an origin to allow.
*/
public void addAllowedOrigin(String origin) {
if (this.allowedOrigins == null) {
this.allowedOrigins = new ArrayList<>(4);
}
else if (this.allowedOrigins == DEFAULT_PERMIT_ALL) {
setAllowedOrigins(DEFAULT_PERMIT_ALL);
}
this.allowedOrigins.add(origin);
}
或者
使用以下
public void setAllowedOrigins(@Nullable List<String> allowedOrigins) {
this.allowedOrigins = (allowedOrigins != null ? new ArrayList<>(allowedOrigins) : null);
}