如何在Spring云网关中禁用CORS?
我想从我的前端应用程序调用POST请求,但在控制台中我看到: CORS策略已阻止从源“”访问“”处的XMLHttpRequest:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源”标头 在my application.yml中:如何在Spring云网关中禁用CORS?,cors,spring-webflux,spring-cloud-gateway,Cors,Spring Webflux,Spring Cloud Gateway,我想从我的前端应用程序调用POST请求,但在控制台中我看到: CORS策略已阻止从源“”访问“”处的XMLHttpRequest:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源”标头 在my application.yml中: spring: application: name: gateway-service cloud: gateway: globalcors: corsConfigurations:
spring:
application:
name: gateway-service
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "localhost:3000"
allowedMethods:
- POST
但是这不起作用,我使用的是HOXTON.RELEASE spring云版本,我的pom.xml文件中没有spring安全依赖项。好的,我找到了解决方案,application.yml中的globalcors部分可能会被删除。您必须实施的是:
@Configuration
public class CORSConfiguration implements WebFluxConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*")
.exposedHeaders(HttpHeaders.SET_COOKIE);
}
@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addExposedHeader(HttpHeaders.SET_COOKIE);
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(corsConfigurationSource);
}
}