Search code examples
angularspring-bootcors

Angular 18 CORS issue with Springboot as backend


I am pretty new to angular 18, I am using springboot as my backend with springsecurity. I am encountering CORS issue while using API request When I'm using GET request to fetch data in ngOnInit, I am getting error but when I reload the page once, the error is gone. For POST request. I'm getting this error:

for POST request

export class ClassesComponent implements OnInit {
  classList$: Observable<any[]> | undefined; // Observable for async pipe
  isModalOpen = false;
  newClass = { classname: '', facultyname: '', description: '' };

  http = inject(HttpClient);
  classesService = inject(ClassserviceService);

  constructor() {
    
  }

  ngOnInit(): void {
    // ngOnInit will run after the component is constructed
    console.log('ngOnInit working...');
    
    this.classList$ = this.classesService.getData(); // Return observable directly
   
  }

  // Method to open modal for creating a new class
  openCreateClassModal() {
    this.isModalOpen = true;
  }

  // Method to close the modal
  closeCreateClassModal() {
    this.isModalOpen = false;
    this.newClass = { classname: '', facultyname: '', description: '' }; // Reset form
  }

  // Method to create a new class
  createClass() {
    this.http.post('http://localhost:8080/api/classes', this.newClass, {
      headers: { 'Content-Type': 'application/json' }
    }).subscribe({
      next: () => {
        // Fetch the updated list of classes after creation
        this.classList$ = this.classesService.getData(); // Update classList$ with new data
        this.closeCreateClassModal(); // Close the modal after creation
      },
      error: (error) => {
        console.error('Error creating class:', error);
      }
    });
  }
}

Solution

  • If you just want to proxy the api call in local development evnironment, please follow the steps below.

    1. Create proxy file

    Create a new file named proxy.conf.json in the root src folder of your Angular project. The content of the file should look like this:

    {
      "/api": {
        "target": "http://localhost:8080",
        "secure": false
      }
    }
    

    In this way, all the api calls start with /api will be proxyed to http://localhost:8080

    2. Set the proxy file in file angular.json

    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "configurations": {
        "production": {
          "browserTarget": "angular-16:build:production"
        },
        "development": {
          "proxyConfig": "src/proxy.conf.json", // <--- Add this line
          "browserTarget": "angular-16:build:development"
        }
      },
    

    3. run ng serve

    Note: Don't call backend api directly when using a proxy, call it with the front-end baseUrl or relative path.

    this.http.get('http://localhost:4200/api/classes'); // OK
    this.http.get('/api/classes'); // OK
    this.http.get('http://localhost:8080/api/classes'); // Won't work!