Search code examples
springcorsspring-cloudspring-cloud-gateway

Resolving CORS issue in React + Spring microservices using Eureka and Spring Cloud Gateway


I have a React + Spring microservices architecture where I've separated my server into microservices and I'm using Eureka along with spring.cloud.gateway. Despite trying various methods, I'm unable to resolve the CORS (Cross-Origin Resource Sharing) issue.

enter image description here

Below are snippets of my class codes:

application.properties in API Gateway:

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

WebConfig in API Gateway:

@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);
    }
}

I've also included a similar WebConfig in my server microservices.

Despite these configurations, CORS issues persist. Can anyone provide guidance on how to properly resolve CORS in a React + Spring microservices setup using Eureka and Spring Cloud Gateway?


Solution

  • The problem with Cors was solved, all that was needed was to change the configuration file application.properties -> application.yml and add the following configuration:

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