CodexBloom - Programming Q&A Platform

Handling CORS implementing Custom Headers in Spring Boot REST API

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
spring-boot cors rest axios webmvc Java

I'm integrating two systems and I recently switched to I'm sure I'm missing something obvious here, but I've looked through the documentation and I'm still confused about I'm currently developing a REST API using Spring Boot 2.7.3, and I'm working with CORS issues when trying to send a request with custom headers from a React frontend... The API is configured to handle CORS, but I keep running into the behavior: `Access-Control-Allow-Origin header is missing`. I've set up a `CorsConfiguration` class as follows: ```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("Content-Type", "Authorization", "Custom-Header") .allowCredentials(true); } } ``` On the frontend, I'm making a request using axios: ```javascript axios.post('http://localhost:8080/api/resource', data, { headers: { 'Custom-Header': 'MyHeaderValue' } }); ``` I've also included the `spring-boot-starter-web` dependency in my `pom.xml`, and I believe that should suffice for handling CORS. However, despite these settings, the browser still blocks the request and shows the behavior message. I've tried clearing the cache and different browsers, but the scenario continues. How can I resolve this CORS behavior when using custom headers in my Spring Boot REST API? My development environment is Linux. What am I doing wrong? Any help would be greatly appreciated! I'm working in a Ubuntu 20.04 environment. I appreciate any insights! Am I missing something obvious? I've been using Java for about a year now. Is there a simpler solution I'm overlooking? The stack includes Java and several other technologies. Could someone point me to the right documentation?