Handling CORS Issues in a Spring Boot REST API with Angular Frontend
I'm confused about I'm upgrading from an older version and I'm working through a tutorial and I'm currently working on a project that consists of a Spring Boot REST API (version 2.5.4) for the backend and an Angular frontend (version 12)... I'm facing a CORS (Cross-Origin Resource Sharing) issue when trying to make API calls from the Angular application to my Spring Boot server. The Angular app is served from `http://localhost:4200`, while the Spring Boot API is running on `http://localhost:8080`. When I attempt to fetch data using the following Angular service: ```typescript import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { private apiUrl = 'http://localhost:8080/api/data'; constructor(private http: HttpClient) {} getData(): Observable<any> { return this.http.get(this.apiUrl); } } ``` I receive the following error in the browser's 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. ``` I have tried adding a `CorsConfigurationSource` bean to 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"); } } ``` However, the CORS issue persists. I've also tried using the `@CrossOrigin` annotation directly on my controller methods: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.CrossOrigin; @RestController @RequestMapping("/api") public class DataController { @CrossOrigin(origins = "http://localhost:4200") @GetMapping("/data") public ResponseEntity<List<Data>> getData() { // return data logic } } ``` Despite these attempts, the error remains unresolved. I've checked the network tab in Chrome and confirmed that the preflight OPTIONS request is being made, but it is not reaching the server. I've also ensured that my Spring Boot application is running without errors. Can someone provide guidance on how to properly configure CORS for my setup? My development environment is Ubuntu 20.04. Thanks in advance! This is happening in both development and production on Linux. I'm open to any suggestions.