CodexBloom - Programming Q&A Platform

Handling CORS Preflight Requests with Spring Boot and Angular for a REST API

👀 Views: 81 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
spring-boot cors angular Java

I'm building a REST API using Spring Boot (version 2.5.4) and a frontend with Angular (version 12.0.0). I'm working with a CORS scenario when making requests from my Angular application to the Spring Boot backend. Specifically, when I try to send a POST request to an endpoint, I get a `CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource` behavior in the browser console. I've configured CORS in my Spring Boot application 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:4200") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true); } } ``` Despite this configuration, I noticed that when I inspect the network requests in the browser, the preflight OPTIONS request fails with a 403 Forbidden behavior. I've also tried adding the `@CrossOrigin` annotation directly on my controller methods, but that didn't change the outcome. Here's an example of one of my controller methods: ```java @RestController @RequestMapping("/api/items") public class ItemController { @CrossOrigin(origins = "http://localhost:4200") @PostMapping public ResponseEntity<Item> createItem(@RequestBody Item item) { // logic to save the item } } ``` I also verified that my Angular HTTP client is configured correctly to include credentials for the requests. However, I'm still exploring with the CORS scenario. Is there something I might be missing in my configuration? Could it be a question with my Spring Security settings? If so, how can I allow CORS while still enforcing authentication? Any insights would be really appreciated!