Soy nuevo utilizando Angular con SpringBoot, en mi proyecto agrego la etiqueta @CrossOrigin para evitar el bloqueo de CORS en la ejecucion de proyecto, pero me sigue saliendo el mismo error.
Error: Access to XMLHttpRequest at 'http://localhost:8080/springboot-crud-rest/api/v1/employees' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
...
import com.exception.ResourceNotFoundException;
import com.model.Employee;
import com.repository.EmployeeRepository;
@CrossOrigin(origins="http://localhost:4200")
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> getAllEmployees(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
return employeeRepository.findAll();
}
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
...
Enn el archivo employee.service.ts de mi proyecto Angular agrego la ruta de mi proyecto SpringBoot.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private baseUrl = 'http://localhost:8080/springboot-crud-rest/api/v1/employees';
constructor(private http: HttpClient) { }
getEmployee(id: number): Observable<any> {
return this.http.get(`${this.baseUrl}/${id}`);
}
createEmployee(employee: Object): Observable<Object> {
return this.http.post(`${this.baseUrl}`, employee);
}
updateEmployee(id: number, value: any): Observable<Object> {
return this.http.put(`${this.baseUrl}/${id}`, value);
}
deleteEmployee(id: number): Observable<any> {
return this.http.delete(`${this.baseUrl}/${id}`, { responseType: 'text' });
}
getEmployeesList(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
}