CodexBloom - Programming Q&A Platform

Spring Boot Application: implementing CORS Configuration for Fetch Requests

👀 Views: 11 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
spring-boot cors reactjs Java

I'm trying to figure out I'm building a feature where I need some guidance on I'm working on a project and hit a roadblock... Hey everyone, I'm running into an issue that's driving me crazy. I'm currently working on a Spring Boot application (version 2.5.4) that serves a REST API. Recently, I set up a front-end application using React (version 17.0.2) that makes fetch requests to my API. However, I'm working with CORS issues. When I try to fetch data from my API, I'm getting the following behavior in the 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 have tried adding CORS mappings in my Spring Boot application 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") .allowedHeaders("*") .allowCredentials(true); } } ``` Despite this, the behavior continues. I also tried adding the following to my application.properties file: ``` spring.web.cors.allowed-origin-patterns=http://localhost:3000 ``` I ensured the React app is running on port 3000 and the Spring Boot app on port 8080. I've restarted both applications after making these changes, but the CORS scenario remains unresolved. Any suggestions on how to properly configure CORS in my Spring Boot application to allow requests from my React app? Any help would be greatly appreciated! I'm on Debian using the latest version of Java. Thanks in advance! What am I doing wrong? This is my first time working with Java 3.11. Is this even possible?