Angular 18 CORS issue with Springboot as backend

Discussão em 'Angular' iniciado por nithikesh bekkary, Setembro 29, 2024.

  1. I am pretty new t angular 18, I am using springboot as my backend with springsecurity. I am encountering CORS issue while using API request When im 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. im 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);
    }
    });
    }
    }

    Continue reading...

Compartilhe esta Página