I have Angular frontend and Springboot backend.
My Springboot controller is annotated with @CorsOrigin
like below which based on my reading will enable CORS on all endpoints in this controller; however that is not the case for some reason:
@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);
}
}
My Angular 9 frontend will use a form to create new Employee. On form submit, I call onSubmit
which calls saveEmployee
which calls 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']);
}
However, when I enter employee information in form and click on Submit button I get the CORS error:
How do I resolve this issue?
I tried to close this question but could not since @Geeth tried helping and answering (Much appreciated @Geeth).
The issue was oversight on my side. I have service in my Angular app with base URL as
"http://localhost:8080/api/v1/employee"
The correct URL is
"http://localhost:8080/api/v1/employees"
This fixed the above issue. Thanks