CORS 配置
您可以配置閘道器以全域性或按路由控制 CORS 行為。兩者提供相同的可能性。
全域性 CORS 配置
“全域性”CORS 配置是將 URL 模式對映到 Spring Framework CorsConfiguration 的對映。以下示例配置了 CORS
application.yml
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "https://docs.springframework.tw"
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