CodexBloom - Programming Q&A Platform

Spring Boot REST API - Handling CORS for a React Frontend with Different Origins

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-18
spring-boot cors react Java

I tried several approaches but none seem to work..... I'm currently developing a Spring Boot REST API (version 2.5.4) that needs to communicate with a React frontend hosted on a different domain. I've enabled CORS in my Spring Boot application, but I'm working with a `CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource` behavior in the browser when trying to make a request from the frontend. I've tried adding a `@CrossOrigin` annotation to my controller like this: ```java @RestController @RequestMapping("/api") @CrossOrigin(origins = "http://localhost:3000") public class MyController { @GetMapping("/data") public ResponseEntity<List<MyData>> getData() { List<MyData> data = myService.getData(); return ResponseEntity.ok(data); } } ``` However, this doesn't seem to resolve the scenario. I also tried defining a global CORS configuration class: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedOrigins("http://localhost:3000").allowedMethods("GET", "POST"); } } ``` Despite these attempts, I continue to see the same CORS behavior in the browser. I've confirmed that my frontend is indeed running on the specified origin and that no proxy is interfering with the requests. Could there be additional configurations needed for CORS to work properly in Spring Boot? Are there any best practices for handling CORS in a mixed-origin environment with a React frontend? Any insights on how to debug this scenario further would be greatly appreciated. This is part of a larger service I'm building. What am I doing wrong? Thanks for taking the time to read this!