Angular(或任何HttpClient)。应用程序中捕获状态码为0的错误,但在Chrome开发工具中状态码不为0?
创始人
2024-11-01 17:00:25
0

这可能是由于浏览器所显示的状态码与服务器发送的状态码不同步导致的。这种情况通常是由于 CORS(跨域资源共享)设置或浏览器安全策略引起的。为了解决这个问题,可以尝试在请求头中添加一些 CORS 相关的选项,如下所示:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class ApiService {
  // Set the API endpoint URL
  private apiUrl = 'http://api.example.com';

  constructor(private http: HttpClient) {}

  // Define the custom headers with CORS options
  private httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, DELETE'
    })
  };

  // Define the custom error handling function
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // Return an observable with a user-facing error message.
    return throwError(
      'Something bad happened; please try again later.');
  };

  // Make the API call with error handling
  getData(): Observable {
    return this.http.get(this.apiUrl, this.httpOptions)
      .pipe(
        catchError(this.handleError)
      );
  }
}

在以上示例中,我们使用了 Access-Control-Allow-Origin (跨域资源共享) 和 Access-Control-Allow-Methods (跨域资源共享)等 CORS 相关的选项,以及 catchError() 操作符处理错误。这样就可以在 Angular 应用程序中捕获并确切地处理错误,而不会因为浏览器不同步而混淆。

相关内容

热门资讯

透视透视"we po... 透视透视"we poker免费辅助器"总是有辅助教程(哔哩哔哩)1、we poker免费辅助器模拟器...
透视揭幕"wepok... 透视揭幕"wepoker能不能透视"切实存在有辅助工具(哔哩哔哩)进入游戏-大厅左侧-新手福利-激活...
透视辅助"wepok... 透视辅助"wepoker免费脚本咨询"好像存在有辅助方法(哔哩哔哩)1、许多玩家不知道wepoker...
透视教你"wepok... 透视教你"wepoker好友房开挂"都是真的是有辅助神器(哔哩哔哩)1、首先打开wepoker好友房...
透视解密"智星菠萝可... 透视解密"智星菠萝可以辅助吗"好像是真的辅助插件(哔哩哔哩)1、这是跨平台的智星菠萝可以辅助吗轻量版...
透视有挂"wejok... 透视有挂"wejoker辅助机器人"都是真的是有辅助工具(哔哩哔哩)1、许多玩家不知道wejoker...
透视解谜"hhpok... 透视解谜"hhpoker是真的假的"好像存在有辅助技巧(哔哩哔哩)hhpoker是真的假的破解侠是真...
透视科普"wepok... 透视科普"wepoker免费脚本弱密码"果然是真的辅助神器(哔哩哔哩)wepoker免费脚本弱密码辅...
透视曝光"pokem... 透视曝光"pokemmo手机版脚本免费"都是是真的辅助脚本(哔哩哔哩)小薇(辅助器软件下载)致您一封...
透视专业"wepok... 透视专业"wepoker透视脚本"一直是真的辅助方法(哔哩哔哩)wepoker透视脚本辅助器是一种具...