【问题标题】:Angular 9 frontend/springboot backend - How to solve CORS error when calling router.navigate(url) [closed]Angular 9前端/springboot后端-调用router.navigate(url)时如何解决CORS错误[关闭]
【发布时间】:2021-10-01 00:53:13
【问题描述】:

我有 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 错误:

我该如何解决这个问题?

【问题讨论】:

    标签: angular spring-boot cors angular-router


    【解决方案1】:

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

    【讨论】:

    • 谢谢。我实际上解决了这个问题,问题是我的服务试图访问无效的 URL。
    【解决方案2】:

    我试图关闭这个问题,但由于@Geeth 尝试帮助和回答(非常感谢@Geeth),所以无法关闭。

    问题是我这边的疏忽。我在我的 Angular 应用中有服务,其基本 URL 为

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

    正确的网址是

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

    这解决了上述问题。谢谢

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 2020-04-20
      • 2021-06-15
      • 2017-06-20
      • 2020-02-07
      • 2018-06-12
      • 1970-01-01
      • 2020-04-29
      • 2021-09-04
      相关资源
      最近更新 更多