我是 t angular 18 的新手,我使用 springboot 作为 springsecurity 的后端。 我在使用 API 请求时遇到 CORS 问题 当我使用 GET 请求在 ngOnInit 中获取数据时,我收到错误,但是当我重新加载页面一次时,错误就消失了。 对于 POST 请求。我收到此错误
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);
}
});
}
}
问题可能出在 spring security 配置上。检查您的配置是否设置为允许来自“http://localhost:8080”的跨源请求 (CORS)
Spring 中不同 cors 配置的一些详细信息可以根据您的实现提供帮助。