使用 Eureka 和 Spring Cloud Gateway 解决 React + Spring 微服务中的 CORS 问题

问题描述 投票:0回答:1

我有一个 React + Spring 微服务架构,我将我的服务器分成了微服务,并使用 Eureka 和 spring.cloud.gateway。尽管尝试了各种方法,我还是无法解决 CORS(跨域资源共享)问题。

以下是我的班级代码片段:

API网关中的application.properties:

server.port=8082
spring.application.name=api-gateway
eureka.client.service-url.defaultZone=http://localhost:8081/eureka
logging.pattern.console=%C{1.} [%-5level] %d[HH:mm:ss] - %msg%n
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-userId=true

spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedOrigins=http://localhost:3000
spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedHeaders=*
spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedMethods[0]=GET
spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedMethods[1]=POST

API网关中的WebConfig:

@Configuration
public class WebConfig {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        source.registerCorsConfiguration("/**", config);
        config.setAllowCredentials(false);
        config.setAllowedHeaders(Collections.singletonList("*"));
        config.setAllowedMethods(Collections.singletonList("*"));
        config.setExposedHeaders(Collections.singletonList("*"));
        config.setAllowedOriginPatterns(Collections.singletonList("*"));
        return new CorsFilter(source);
    }
}

我还在我的服务器微服务中包含了类似的 WebConfig。

尽管有这些配置,CORS 问题仍然存在。任何人都可以提供有关如何使用 Eureka 和 Spring Cloud Gateway 在 React + Spring 微服务设置中正确解决 CORS 的指导吗?

spring cors spring-cloud spring-cloud-gateway
1个回答
0
投票

Cors的问题解决了,只需要修改配置文件application.properties -> application.yml,添加如下配置即可:

spring:
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods:
              - GET
              - POST
© www.soinside.com 2019 - 2024. All rights reserved.