CodexBloom - Programming Q&A Platform

Java 17: implementing Spring Boot CORS Configuration for React Frontend

👀 Views: 11 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
spring-boot cors react java-17 Java

I need some guidance on Hey everyone, I'm running into an issue that's driving me crazy... I've been struggling with this for a few days now and could really use some help. I'm developing a Spring Boot application using Java 17 and trying to set up CORS for my React frontend. Despite configuring CORS in my `WebMvcConfigurer`, I'm still receiving a `403 Forbidden` behavior when my React app tries to access an API endpoint. I've tried the following configuration in my `WebConfig` class: ```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") .allowedHeaders("*") .allowCredentials(true); } } ``` I also made sure to set up my React app to point to the correct API URL, and I've confirmed that the backend is running on `http://localhost:8080`. However, I still see the following behavior in the browser console: ``` Access to fetch at 'http://localhost:8080/api/data' 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 tested the API endpoints using Postman, and they work perfectly fine without CORS issues. I've also tried adding the `@CrossOrigin` annotation directly to my controller method, but that didn't help either: ```java @RestController @RequestMapping("/api") public class DataController { @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/data") public ResponseEntity<List<Data>> getData() { // ... fetch data logic return ResponseEntity.ok(dataList); } } ``` Any idea on what might be causing this CORS scenario, or how to debug further? I've checked my Spring Boot version (2.6.7) and everything seems up to date. I'm really exploring on this and would appreciate any insight! For context: I'm using Java on Windows. Thanks in advance! Any ideas how to fix this?