CORS 配置
你可以配置网关来控制全局或每个路由的CORS 行为。两者都提供相同的配置选项。
全局 CORS 配置
“全局”CORS配置是一个URL模式到Spring Framework CorsConfiguration的映射。以下示例配置了CORS:
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "https://docs.spring.io"
allowedMethods:
- GET
在前面的示例中,允许来自 docs.spring.io 的 CORS 请求访问所有 GET 请求路径。
要为未由某些网关路由谓词处理的请求提供相同的 CORS 配置,请将 spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping 属性设置为 true。当您尝试支持 CORS 预检请求,且由于 HTTP 方法为 options 导致路由谓词未评估为 true 时,此设置非常有用。
路由 CORS 配置
“route”配置允许将CORS直接作为元数据应用于路由,其键为cors。与全局配置的情况类似,这些属性属于Spring Framework CorsConfiguration。
备注
如果路由中没有 Path 谓词,将应用 '/**'。
spring:
cloud:
gateway:
routes:
- id: cors_route
uri: https://example.org
predicates:
- Path=/service/**
metadata:
cors:
allowedOrigins: '*'
allowedMethods:
- GET
- POST
allowedHeaders: '*'
maxAge: 30