【问题标题】:How to disable CORS in Spring Cloud Gateway?如何在 Spring Cloud Gateway 中禁用 CORS?
【发布时间】:2020-09-06 14:46:12
【问题描述】:

我想从我的前端应用程序调用一个 POST 请求,但是在控制台中我看到:

从源“http://localhost:3000”访问“http://localhost:9090/authenticate”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。

在我的 application.yml 中:

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "localhost:3000"
            allowedMethods:
              - POST

但是这不起作用,我使用的是 HOXTON.RELEASE spring-cloud 版本,我的 pom.xml 文件中没有 spring 安全依赖项。

【问题讨论】:

    标签: cors spring-webflux spring-cloud-gateway


    【解决方案1】:

    好的,我找到了解决方案,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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-22
      • 2021-06-04
      • 1970-01-01
      • 2020-07-13
      • 2021-07-13
      • 1970-01-01
      • 2019-10-29
      • 2021-08-27
      • 2019-06-15
      相关资源
      最近更新 更多