使用 Spring Gateway 并收到错误:“Access-Control-Allow-Origin”标头包含多个值“*、*”,但只允许一个

vla*_*sky 9 spring-boot

我使用 Spring Gateway 框架并配置如下。

 gateway:
  default-filters:
    - DedupeResponseHeader=Access-Control-Allow-Origin
  globalcors:
    cors-configurations:
      '[/**]':
        allowedOrigins: "*"
        allowedMethods: "*"
        allowedHeaders: "*"
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在网关上执行请求时,出现以下错误。

已被 CORS 策略阻止:“Access-Control-Allow-Origin”标头包含多个值“*、*”,但只允许一个。

我不明白如何配置以避免此错误

Pab*_*997 13

尝试使用此配置:

spring:
  cloud:
    gateway:
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_UNIQUE
      globalcors:
          cors-configurations:
             '[/**]':
             allowed-origins: "*"
             allowed-methods: "*"
             allowed-headers: "*"
             allow-credentials: true
Run Code Online (Sandbox Code Playgroud)

  • 对于 Spring Cloud 2022.0.3,我得到“原因:org.springframework.core.convert.ConverterNotFoundException:找不到能够从类型 [java.lang.String] 转换为类型 [org.springframework.web.cors.CorsConfiguration] 的转换器”知道正确的配置应该是什么吗? (2认同)

小智 8

除了 Pablo 的回答之外,请确保下游服务没有配置 cors,因为它们会将其标头添加到最终的响应标头中。因此,您只需为网关服务配置 cors,并且可以关闭其他服务的端口,以便只能从服务器内部访问它们。