CodexBloom - Programming Q&A Platform

Spring MVC: implementing CORS Configuration Causing Preflight Requests to scenarios

👀 Views: 1695 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-07
spring-mvc cors http web Java

I've searched everywhere and can't find a clear answer. I'm working with an scenario with CORS configuration in my Spring MVC application. I'm trying to allow cross-origin requests from a specific domain, but the preflight OPTIONS request is failing with a 403 Forbidden behavior. I'm using Spring Framework 5.3.10 and have configured CORS globally in my WebMvcConfigurer implementation. Here is what I've set up: ```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://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } } ``` I've ensured that my API endpoints start with `/api/` as specified in the `addMapping` method. However, when I try to make a request from my frontend application (which is hosted on `http://localhost:3000`), the browser shows a CORS behavior in the console: ``` Access to XMLHttpRequest at 'http://localhost:8080/api/resource' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ``` I've also tried adding specific headers for the allowed origins directly in my controller methods, but that didn't help. My server is running on Tomcat, and I verified that there are no conflicting CORS filters or settings in the `web.xml`. Has anyone encountered this scenario before, or can you provide guidance on what might be missing or misconfigured? I'm working on a service that needs to handle this.