Spring WebFlux Cors konfigurieren

DrPils

Bekanntes Mitglied
Hi
Wenn ich einen Endpoint meienr Spring Boot WebFlux Application in meiner React App aufrufe bekomme ich
Code:
ccess to fetch at 'http://localhost:8080/graphql/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Ich habe folgende Configuration Klasse angelegt:
Java:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
public class CorsConfig {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.applyPermitDefaultValues();
        configuration.setAllowedOrigins(List.of("http://localhost:3000"));
        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
 
Ok bei Webflux funktioniert das wohl über den WebFluxConfigurer

Java:
@Configuration

public class CorsConfig {

    

    @Bean

    public WebFluxConfigurer corsConfigurer() {

        return new WebFluxConfigurer() {

            @Override

            public void addCorsMappings(CorsRegistry registry) {

                registry.addMapping("/**")

                        .allowedOrigins("*")

                        .allowedHeaders("*");

            }

        };

    }

}
 

Zurück
Oben