CodexBloom - AI-Powered Q&A Platform

Java Spring Boot CORS Configuration Not Working for Specific Endpoint

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-08
spring-boot cors webmvc javascript

I'm facing an issue with CORS configuration in my Spring Boot application. I've set up CORS for most of my endpoints globally, but it seems that one specific endpoint is still being blocked by the browser. Here's how I've configured CORS globally in my `WebMvcConfigurer` implementation: ```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/**") // This allows CORS for all endpoints under /api .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } } ``` Yet, when I try to access the `/api/specific-endpoint` from my frontend running on `http://localhost:3000`, I still receive a CORS error in the browser console: ``` Access to XMLHttpRequest at 'http://localhost:8080/api/specific-endpoint' 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 checked the endpoint's controller and it looks like this: ```java @RestController @RequestMapping("/api") public class MyController { @GetMapping("/specific-endpoint") public ResponseEntity<String> getSpecificData() { return ResponseEntity.ok("This is some data."); } } ``` I've also tried adding `@CrossOrigin` directly on the controller method: ```java @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/specific-endpoint") public ResponseEntity<String> getSpecificData() { return ResponseEntity.ok("This is some data."); } ``` But that didn’t resolve the issue either. I even restarted the Spring Boot application and cleared my browser cache. Is there something I'm missing or any specific configurations that I should check for this endpoint to ensure CORS is working as expected?