Angular 9 frontend/springboot 后端 - 调用 router.navigate(url) 时如何解决 CORS 错误

Angular 9 frontend/springboot backend - How to solve CORS error when calling router.navigate(url)

我有 Angular 前端和 Springboot 后端。

我的 Springboot 控制器用 @CorsOrigin 注释,如下所示,根据我的阅读,将在该控制器的所有端点上启用 CORS;然而,由于某些原因,情况并非如此:

@CrossOrigin(origins = "http://localhost:4200") // to prevent CORS error in Angular, use url of Angular app
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController {

    @Autowired
    private EmployeeRepository employeeRepository;
    
    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }
    
    @PostMapping("/employees/add")
    public Employee createEmployee(@RequestBody Employee employee) {
        return employeeRepository.save(employee);
    }
}

我的 Angular 9 前端将使用一个表单来创建新员工。在表单提交上,我调用 onSubmit 调用 saveEmployee 调用 goToEmployeeList:

  onSubmit() {
    console.log(this.employee);
    this.saveEmployee();
  }

 saveEmployee() {
    this.employeeService.createEmployee(this.employee).subscribe(data => {
      console.log(data);
      this.goToEmployeeList();
    },
    error => console.log(error));
  }

  /* Once we add new employee, we want to navigate to employee list, so we add new method
     here to use router for that. */
  goToEmployeeList() {
    this.router.navigate(['employees']);
  }

但是,当我在表单中输入员工信息并单击“提交”按钮时,出现 CORS 错误:

如何解决这个问题?

最后@RequestMapping中的“/”应该去掉。应该是@RequestMapping("/api/v1")。试试这个。因为你的 API 端点以“/”开头。

我试图关闭这个问题,但无法关闭,因为@Geeth 尝试提供帮助和回答(非常感谢@Geeth)。

这个问题是我这边的疏忽。我的 Angular 应用程序中有服务,基础 URL 为

"http://localhost:8080/api/v1/employee"

正确的URL是

"http://localhost:8080/api/v1/employees"

这解决了上述问题。谢谢