1

我正在尝试使用 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();
}

}

应用程序.yml

server:
  port: 8080

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods:
              - GET

构建.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")
}
4

2 回答 2

0

这里同样的问题。使用 Ilford (Spring Cloud 2020.0.1) 和 Spring cloud Gateway 3.0.0

预检请求(OPTIONS)总是被配置拒绝

唯一的解决方案是使用添加新 Bean 的代码进行操作,如此处所述

于 2021-02-18T15:13:31.957 回答
-2

默认情况下,API Gateway 为所有源启用 CORS,如果您只想允许列入白名单的源,请使用 globalcors 配置。
spring: cloud: gateway: globalcors: corsConfigurations: '[/**]': allowedOrigins: "*" allowedMethods: - GET

于 2019-01-30T06:54:56.683 回答