CodexBloom - Programming Q&A Platform

Struggling with CORS Configuration in Spring Boot REST API - Preflight Request Fails

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-09-06
Spring CORS REST Spring Boot Java

I'm trying to configure I've been banging my head against this for hours. I'm working on a project and hit a roadblock. I tried several approaches but none seem to work. I'm having trouble with CORS configuration in my Spring Boot REST API. My front-end application is making requests to the API, but I'm encountering a CORS policy error that says `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 tried adding a CORS configuration class that looks like this: ```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").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); } } ``` I also have `@CrossOrigin` annotations on my controller methods like this: ```java @RestController @RequestMapping("/api") public class MyController { @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/resource") public ResponseEntity<Resource> getResource() { // ... } } ``` I double-checked that the front-end is running on port 3000 and the API on port 8080. The issue persists even after clearing my browser cache. Additionally, I noticed that the preflight OPTIONS request fails with a 404 status, which seems to indicate that the API server isn’t handling it correctly. I’ve tried debugging with Postman and noticed that if I make a direct GET request to the same endpoint without CORS, it works perfectly. Does anyone have insights on what might be misconfigured or how to properly set up CORS in a Spring Boot application? Are there any common pitfalls or additional configurations I might be missing? For context: I'm using Java on Linux. Any ideas what could be causing this? My development environment is macOS. Any ideas what could be causing this? This is my first time working with Java 3.10. Thanks in advance! I've been using Java for about a year now. Any ideas what could be causing this?