繁体   English   中英

Angular:http 的 Http 失败响应://localhost:8082/employee/all: 0 未知错误

[英]Angular : Http failure response for http://localhost:8082/employee/all: 0 Unknown Error

我正在尝试使用 Angular 的 HttpClient 模块从 Spring Boot 后端获取员工列表,但出现错误“http://localhost:8082/employee/all: 0 未知错误的 Http 失败响应。 “ 在我的 Angular 应用程序中。

这是我的 app.component.ts 文件:

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);
      }
    )
  }
}

这是我的 employee.service.ts 文件:

@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}`
    );
  }
}

这是后端的终端 output:

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

HTTP/1.1 200 内容类型:应用程序/json 传输编码:分块日期:2023 年 1 月 27 日星期五 16:00:06 GMT 保持活动状态:超时 = 60 连接:保持活动状态

[ { "id": 5, "name": "Millard Gerhartz", "email": "mgerhartz0@so.net.ne.jp", "jobTitle": "业务系统开发分析师", "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" , "员工代码": "a0154f0f-5e8e-4456-8cb6-93f693dbf462" } ]

响应码:200; 时间:157ms; 内容长度:610字节

It seems like employees list is always empty

我通过添加 CorsFilter Bean 在 Spring Boot 中解决了我自己的问题

尝试将我的 Angular 前端应用程序连接到我的 Spring 启动后端 API 时,我遇到了 CORS 问题。经过一些研究,我通过向我的 Spring 启动应用程序添加一个 CorsFilter Bean 解决了这个问题。

这是我在 Spring Boot 应用程序的主要方法下添加的代码:

@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);
}

此代码创建一个 CorsFilter bean 并使用必要的设置对其进行配置以允许来自指定源的请求(在本例中为“http://localhost:4200”)并设置允许的各种标头和方法。 这解决了 CORS 问题并允许我的前端应用程序与后端 API 进行通信。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM