CodexBloom - Programming Q&A Platform

scenarios Implementing CORS in a Spring Boot REST API with WebFlux

👀 Views: 42 💬 Answers: 1 📅 Created: 2025-06-14
spring-boot webflux cors Java

I'm learning this framework and I'm confused about I'm performance testing and I've hit a wall trying to I'm trying to configure I'm currently developing a Spring Boot REST API using WebFlux and I need to enable CORS for specific routes... However, I've run into issues where the CORS configuration doesn't seem to be applied, resulting in a persistent `CORS preflight request doesn't pass access control check: It does not have HTTP status in the 'access-control-allow-origin' header`. I've tried configuring CORS globally using `WebFluxConfigurer`, but it does not seem to work as expected. Here’s what I’ve attempted: In my main configuration class, I have the following code: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.config.CorsRegistry; import org.springframework.web.reactive.config.WebFluxConfigurer; import org.springframework.web.reactive.config.EnableWebFlux; @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true); } } ``` Despite this configuration, when I make a request from my React frontend, I still get the same CORS behavior. I've confirmed that the frontend is running on the specified origin and the routes I’m trying to access are indeed under `/api/**`. I’ve also tried explicitly setting CORS headers in my controller like so: ```java @GetMapping(value = "/data", produces = MediaType.APPLICATION_JSON_VALUE) public Mono<ResponseEntity<Data>> getData() { return Mono.just(ResponseEntity.ok() .header("Access-Control-Allow-Origin", "http://localhost:3000") .body(new Data())); } ``` This still does not resolve the CORS scenario. I’m unsure if there’s a specific order in which the configuration is being applied or if there might be a conflict with other filters or security settings. Any insights on how to properly set up CORS with Spring WebFlux or suggestions for debugging this scenario would be greatly appreciated. Any examples would be super helpful. Any ideas how to fix this? For reference, this is a production mobile app. Could someone point me to the right documentation? This is for a desktop app running on Ubuntu 22.04. I recently upgraded to Java stable. Has anyone else encountered this?