CORS 配置

您可以配置网关以全局或按路由控制 CORS 行为。两者提供相同的可能性。

全局 CORS 配置

“全局”CORS 配置是将 URL 模式映射到 Spring Framework CorsConfiguration 的映射。以下示例配置了 CORS

application.yml
spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "https://docs.springjava.cn"
            allowedMethods:
            - GET

在前面的示例中,CORS 请求允许来自 docs.spring.io 的所有 GET 请求路径。

要为未由某些网关路由谓词处理的请求提供相同的 CORS 配置,请将 spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping 属性设置为 true。当您尝试支持 CORS 预检请求并且您的路由谓词未评估为 true(因为 HTTP 方法是 options)时,这很有用。

路由 CORS 配置

“路由”配置允许将 CORS 直接应用于路由,作为键为 cors 的元数据。与全局配置一样,这些属性属于 Spring Framework CorsConfiguration

如果路由中不存在 Path 谓词,则将应用 '/**'。
application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: cors_route
        uri: https://example.org
        predicates:
        - Path=/service/**
        metadata:
          cors:
            allowedOrigins: '*'
            allowedMethods:
              - GET
              - POST
            allowedHeaders: '*'
            maxAge: 30
© . This site is unofficial and not affiliated with VMware.