我正在尝试使用Spring Cloud Gateway构建网关代理。
我能够使用Spring Cloud中的RouteLocator将请求路由到相应的服务。但是我无法为通过RouteLocator路由的路径配置CORS。
我尝试了Spring Cloud文档中提到的所有可能性。
我的代码看起来像 Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// tag::route-locator[]
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/order/**")
.filters(f -> f.setResponseHeader("Access-Control-Allow-Origin", "http://localhost:8081")
)
.uri("http://localhost:9090"))
.route(p -> p
.path("/priority-model/selection/**")
.filters(f -> f.addResponseHeader("Access-Control-Allow-Origin", "http://localhost:8081")
)
.uri("http://localhost:9090"))
.build();
}
}
application.yml
server:
port: 8080
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedMethods:
- GET
buils.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'gs-gateway'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.SR2"
}
}
dependencies {
compile("org.springframework.cloud:spring-cloud-starter-gateway")
compile("org.springframework.cloud:spring-cloud-starter-netflix-hystrix")
compile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner"){
exclude group: "org.springframework.boot", module: "spring-boot-starter-web"
}
compile group: 'org.springframework.cloud', name: 'spring-cloud-gateway-webflux', version: '2.0.2.RELEASE'
testCompile("org.springframework.boot:spring-boot-starter-test")
}
答案 0 :(得分:0)
默认情况下,API网关对所有来源启用CORS,如果您只允许列入白名单的来源,则使用globalcors配置。
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedMethods:
- GET
答案 1 :(得分:0)
同样的问题。 使用 Ilford (Spring Cloud 2020.0.1) 和 Spring Cloud Gateway 3.0.0
预检请求(OPTIONS)总是被配置拒绝
唯一的解决方案是使用代码添加一个新的 Bean,如here