0

I'm trying to fetch a list of employees from a Spring Boot back-end using Angular's HttpClient module, but I'm getting the error "Http failure response for http://localhost:8082/employee/all: 0 Unknown Error." in my Angular app.

Here's my app.component.ts file:

export class AppComponent implements OnInit {
  public employees: Employee[] | undefined;

  constructor(private employeeService: EmployeeService) {}

  ngOnInit(): void {
    this.getEmployees();
  }

  public getEmployees(): void {
    this.employeeService.getEmployees().subscribe(
      (response: Employee[]) => {
        this.employees = response;
      },
      (error: HttpErrorResponse) => {
        alert(error.message);
      }
    )
  }
}

And here's my employee.service.ts file:

@Injectable({
  providedIn: 'root',
})
export class EmployeeService {
  private apiServerUrl = environment.apiBaseUrl;

  constructor(private http: HttpClient) {}

  public getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(`${this.apiServerUrl}/employee/all`);
  }

  public addEmployee(employee: Employee): Observable<Employee> {
    return this.http.post<Employee>(
      `${this.apiServerUrl}/employee/add`,
      employee
    );
  }

  public updateEmployee(employee: Employee): Observable<Employee> {
    return this.http.put<Employee>(
      `${this.apiServerUrl}/employee/update`,
      employee
    );
  }

  public deleteEmployee(employeeId: number): Observable<void> {
    return this.http.delete<void>(
      `${this.apiServerUrl}/employee/delete/${employeeId}`
    );
  }
}

And here is the terminal output from the back-end:

GET http://localhost:8082/employee/all

HTTP/1.1 200 Content-Type: application/json Transfer-Encoding: chunked Date: Fri, 27 Jan 2023 16:00:06 GMT Keep-Alive: timeout=60 Connection: keep-alive

[ { "id": 5, "name": "Millard Gerhartz", "email": "mgerhartz0@so-net.ne.jp", "jobTitle": "Business Systems Development Analyst", "phone": "487-530-7589", "imageUrl": "https://img.freepik.com/free-photo/close-up-young-successful-man-smiling-camera-standing-casual-outfit-against-blue-background_1258-66609.jpg?w=2000", "employeeCode": "4d6ca12b-94fc-4d64-8ea3-d4c3e2cfdfc3" }, { "id": 6, "name": "Terencio Stoate", "email": "tstoate0@howstuffworks.com", "jobTitle": "Budget/Accounting Analyst II", "phone": "936-713-6713", "imageUrl": "http://dummyimage.com/147x100.png/cc0000/ffffff", "employeeCode": "a0154f0f-5e8e-4456-8cb6-93f693dbf462" } ]

Response code: 200; Time: 157ms; Content length: 610 bytes

It seems like employees list is always empty
Rami
  • 21
  • 9
  • 1
    have you checked CORS configuration? – Swanand Taware Jan 27 '23 at 16:46
  • Does this answer your question? [I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular](https://stackoverflow.com/questions/47180634/i-get-http-failure-response-for-unknown-url-0-unknown-error-instead-of-actu) – Swanand Taware Jan 27 '23 at 16:47
  • @SwanandTaware you're right, the problem was in CORS config but the link you provided doesn't solved the problem – Rami Jan 27 '23 at 17:23

1 Answers1

0

I resolved my own issues in Spring Boot by adding a CorsFilter Bean

I was running into CORS issues when trying to connect my Angular front-end application to my Spring Boot back-end API. After some research, I resolved the issue by adding a CorsFilter Bean to my Spring Boot application.

Here is the code I added under the main method in my Spring Boot application:

@Bean
public CorsFilter corsFilter() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
            "Accept", "Authorization", "Origin, Accept", "X-Requested-With",
            "Access-Control-Request-Method", "Access-Control-Request-Headers"));
    corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
            "Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
    corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
    return new CorsFilter(urlBasedCorsConfigurationSource);
}

This code creates a CorsFilter bean and configures it with the necessary settings to allow requests from the specified origin ("http://localhost:4200" in this case) and sets various headers and methods that are allowed. This resolved the CORS issues and allowed my front-end application to communicate with the back-end API.

Rami
  • 21
  • 9