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

epggiuax  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(40)

我有一个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的指导吗?

niwlg2el

niwlg2el1#

Cors的问题已经解决了,所需要的只是更改配置文件application.properties-> application.yml并添加以下配置:

spring:
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods:
              - GET
              - POST

字符串

相关问题