Handling CORS Issues When Consuming REST API in Angular 14 with Spring Boot Backend
I've been working on this all day and I'm currently building a web application using Angular 14 as the frontend and Spring Boot 2.6.3 for the backend. I've set up a REST API in my Spring Boot application, but I'm running into CORS (Cross-Origin Resource Sharing) issues when trying to consume the API from my Angular app. When I make an HTTP request from Angular to my Spring Boot API, I'm getting the following error in the browser console: ``` Access to XMLHttpRequest at 'http://localhost:8080/api/data' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ``` To resolve this, I've tried adding a CORS mapping 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:4200").allowedMethods("GET", "POST", "PUT", "DELETE"); } } ``` However, I'm still facing the same CORS issue. I've also ensured that the API endpoint is correctly set up and that I'm hitting the right URL. I even tried using the `@CrossOrigin` annotation directly on my controller: ```java import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @CrossOrigin(origins = "http://localhost:4200") @RestController public class DataController { @GetMapping("/api/data") public String getData() { return "Hello from Spring Boot!"; } } ``` Despite these attempts, the CORS issue persists. Are there additional configurations or steps I might be missing? Is there a better approach to handle CORS in a Spring Boot application? Any insights into troubleshooting this would be greatly appreciated! This is part of a larger service I'm building. Am I missing something obvious? This is my first time working with Java 3.11. Is this even possible? This issue appeared after updating to Java LTS.