Spring Boot REST API: How to Handle CORS implementing Preflight Requests in Angular
I'm refactoring my project and I'm working on a project and hit a roadblock. I'm building a Spring Boot REST API (version 2.6.4) and an Angular frontend (version 12.2.0). Recently, I started working with issues related to Cross-Origin Resource Sharing (CORS). When my Angular application tries to access the API, it often fails during the preflight OPTIONS request, resulting in a `CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` behavior. I've been trying to configure CORS in my Spring Boot application using the `WebMvcConfigurer` interface. Below is the code I've implemented: ```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("/**").allowedOrigins("http://localhost:4200").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); } } ``` Despite this configuration, I still encounter the CORS scenario, particularly when making requests that include custom headers. I've also tried adding `@CrossOrigin` annotations on my controller methods, but that did not solve the question either. Here’s an example of one of my controller methods: ```java @RestController @RequestMapping("/api/v1/data") public class DataController { @CrossOrigin(origins = "http://localhost:4200") @GetMapping("/items") public ResponseEntity<List<Item>> getItems() { List<Item> items = itemService.getAllItems(); return ResponseEntity.ok(items); } } ``` I’ve also verified that the Angular application is indeed running on port 4200, and I’ve checked the network tab in the browser’s developer tools to confirm the OPTIONS request is being sent, but no `Access-Control-Allow-Origin` header returns in the response. Could there be something I've missed in the configuration, or is there an alternative approach to resolving this CORS scenario? Any advice or examples would be greatly appreciated! Hoping someone can shed some light on this. For context: I'm using Java on Windows 10. Is this even possible?