在 httpclient 中检测来自服务器的 http 404 响应

Detect http 404 responses from server in httpclient

我在检测 api 的 404 响应状态时遇到问题。如果您查看图像,您会看到 chrome 正确记录了请求的 404 响应状态。问题是 angular 的 http 客户端正在报告状态代码“0”。我在这里做错了什么...?

代码:

checkNameTaken(clientId: string, name: string): Observable<boolean> {
const baseUrl = this.configService.configBs.getValue().apiBaseUrl;
return this.http.get(`${baseUrl}/Rules/${clientId}/${name}`)
  .pipe(
    catchError( error => {
      if ( !(error.error instanceof ErrorEvent)) {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        if (error.status === '404') {
          return of(true);
        }
        console.error(
          `Backend returned code ${error.status}, ` +
          `body was: ${error.error}`);
      }
      return of(false);
    }),
    map(rule => rule ? true : false)
  );

}

这是来自 chrome 的网络选项卡:

Request URL: http://localhost:57067/api/Rules/C7000050/tests
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:57067
Referrer Policy: no-referrer-when-downgrade

知道为什么 error.status 在服务器 returns 出现 404 时总是返回 0 吗? 运行 Angular 7.2.0

将代码更新为:

checkNameTaken(clientId: string, name: string): Observable<boolean> {
    const baseUrl = this.configService.configBs.getValue().apiBaseUrl;
    return this.http.get(`${baseUrl}/Rules/${clientId}/${name}`)
      .pipe(
        catchError( error => {
          if ( !(error.error instanceof ErrorEvent)) {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            if (error.status === 404) {
              return of(true);
            }
            console.error(
              `Backend returned code ${error.status}, ` +
              `body was: ${error.error}`);
          }
          return of(false);
        }),
        map(rule => rule ? true : false)
      );
  }

error.status 在服务器 returns 404 时仍然始终为 0。

状态码是数字而非字符串。

checkNameTaken(clientId: string, name: string): Observable<boolean> {
const baseUrl = this.configService.configBs.getValue().apiBaseUrl;
return this.http.get(`${baseUrl}/Rules/${clientId}/${name}`)
  .pipe(
    catchError( error => {
      if ( !(error.error instanceof ErrorEvent)) {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        if (error.status === 404) {
          return of(true);
        }
        console.error(
          `Backend returned code ${error.status}, ` +
          `body was: ${error.error}`);
      }
      return of(false);
    }),
    map(rule => rule ? true : false)
  );
}

如果不是这种情况,可能是这里提到的 CORS 问题:https://github.com/angular/angular/issues/20991