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

epggiuax  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(138)

我有一个React + Spring微服务架构,我已经将我的服务器分成了多个微服务,我正在使用Eureka 沿着spring.cloud.gateway。尽管尝试了各种方法,但我无法解决CORS(跨源资源共享)问题。


的数据
下面是我的类代码的片段:
API网关中的application.properties:

  1. server.port=8082
  2. spring.application.name=api-gateway
  3. eureka.client.service-url.defaultZone=http://localhost:8081/eureka
  4. logging.pattern.console=%C{1.} [%-5level] %d[HH:mm:ss] - %msg%n
  5. spring.cloud.gateway.discovery.locator.enabled=true
  6. spring.cloud.gateway.discovery.locator.lower-case-service-userId=true
  7. spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedOrigins=http://localhost:3000
  8. spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedHeaders=*
  9. spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedMethods[0]=GET
  10. spring.cloud.gateway.globalcors.corsConfigurations['[/**]'].allowedMethods[1]=POST

字符串
API网关中的WebConfig:

  1. @Configuration
  2. public class WebConfig {
  3. @Bean
  4. public CorsFilter corsFilter() {
  5. final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  6. CorsConfiguration config = new CorsConfiguration();
  7. source.registerCorsConfiguration("/**", config);
  8. config.setAllowCredentials(false);
  9. config.setAllowedHeaders(Collections.singletonList("*"));
  10. config.setAllowedMethods(Collections.singletonList("*"));
  11. config.setExposedHeaders(Collections.singletonList("*"));
  12. config.setAllowedOriginPatterns(Collections.singletonList("*"));
  13. return new CorsFilter(source);
  14. }
  15. }


我还在我的服务器微服务中包含了一个类似的WebConfig。
尽管有这些配置,CORS问题仍然存在。有人能提供如何使用Eureka 和Spring Cloud Gateway在React + Spring微服务设置中正确解决CORS的指导吗?

niwlg2el

niwlg2el1#

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

  1. spring:
  2. cloud:
  3. gateway:
  4. globalcors:
  5. add-to-simple-url-handler-mapping: true
  6. corsConfigurations:
  7. '[/**]':
  8. allowedOrigins: "*"
  9. allowedHeaders: "*"
  10. allowedMethods:
  11. - GET
  12. - POST

字符串

相关问题