CodexBloom - Programming Q&A Platform

Spring Boot REST API: Handling CORS Issues for Preflight Requests on Custom Endpoints

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-24
spring-boot cors rest-api Java

Does anyone know how to I'm dealing with I'm prototyping a solution and I've encountered a strange issue with I'm stuck on something that should probably be simple... I'm experiencing difficulties with CORS when making a POST request to my Spring Boot REST API from a front-end application hosted on a different domain. The preflight OPTIONS request is returning a '403 Forbidden' response, even though I've configured CORS settings in my `WebMvcConfigurer` implementation. Here’s what I have: ```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.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true); } } ``` I'm using Spring Boot 2.5.4 and this configuration seems correct. However, when I perform a fetch from my React app: ```javascript fetch('http://localhost:8080/api/resource', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) }) .then(response => response.json()) .then(data => console.log(data)); ``` I see the preflight OPTIONS request in the browser's network tab, but it gets blocked with a 'CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.' I've tried adding various allowed headers, but nothing seems to work. I've also ensured that the API endpoint `/api/resource` is defined correctly and that no security filters are interfering. Has anyone encountered this issue and can provide insights on what I might be missing? I'm working on a web app that needs to handle this. I'm using Java 3.11 in this project. Thanks for taking the time to read this! I'm working with Java in a Docker container on Ubuntu 22.04. I'm open to any suggestions. My development environment is Windows 11.