Java Spring Boot: How to Properly Handle CORS for an Angular Frontend?
After trying multiple solutions online, I still can't figure this out. I've been working on this all day and I'm upgrading from an older version and I've searched everywhere and can't find a clear answer... I've been trying to enable CORS for my Spring Boot application that's serving a REST API, which my Angular frontend will consume. Despite configuring CORS in my `WebMvcConfigurer`, I'm still running into issues. When making requests from my Angular app, I receive the following behavior: ``` 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. ``` Here's the configuration I've added to my Spring Boot application: ```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.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedOrigins("http://localhost:4200").allowedMethods("GET", "POST", "PUT", "DELETE"); } } ``` I also tried adding CORS mappings directly in my controller: ```java @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class DataController { @GetMapping("/data") public ResponseEntity<List<Data>> getData() { // method implementation } } ``` Unfortunately, neither of these approaches worked. I've checked that both applications are running on their respective ports, and I'm using Spring Boot 2.5.4. I even tried clearing the browser cache and using incognito mode to ensure that there werenβt any lingering issues. What am I missing here? Is there a specific configuration that I need to implement to get CORS working correctly between my Spring Boot backend and Angular frontend? For context: I'm using Java on macOS. This is happening in both development and production on CentOS. What's the best practice here? I recently upgraded to Java latest. Thanks, I really appreciate it! I'm working on a REST API that needs to handle this.