CodexBloom - Programming Q&A Platform

Handling CORS Preflight Requests in Spring Boot REST API with Multiple Origins

👀 Views: 1196 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-21
spring-boot cors rest-api Java

I'm maintaining legacy code that I'm trying to set up a Spring Boot REST API that needs to handle CORS requests from multiple origins..... However, I'm running into issues with preflight requests returning a 403 Forbidden error when the browser attempts to send a POST request from a different domain. I've already configured CORS in my `WebMvcConfigurer` but it seems that the preflight requests aren't being handled correctly. Here's my current configuration: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:3000", "http://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true); } } ``` Despite this configuration, when I make a POST request from my React frontend, I see the following error in the console: ``` Access to fetch at 'http://localhost:8080/api/resource' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. ``` I've also tried adjusting the allowed origins to `*` to see if that would resolve the issue, but I still faced the same error. I've confirmed that my API is running on `http://localhost:8080` and that the frontend is indeed being served from `http://localhost:3000`. Could this be related to how I'm sending the request? Here's how I'm making the fetch call: ```javascript fetch('http://localhost:8080/api/resource', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ key: 'value' }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` I'm thinking that there might be an issue with Spring Boot not recognizing the preflight OPTIONS request correctly. Has anyone encountered this issue before and can provide insight on how to fix it? Is there a better approach? This issue appeared after updating to Java 3.10. The project is a microservice built with Java.