首页 > 解决方案 > Angular 6 - 429 响应处理

问题描述

如何在 Angular 6 的 HttpClient 上捕获 429 错误响应?

下面的示例将正确捕获 401 错误,但对于 429,它会反馈一个未知错误。

错误/编辑:预检选项检查失败。

登录代码:

this.http.post<any>(this._loginUrl, this.loginUserData)
  .subscribe(
    res => {
      console.log(res)
    },
    err => {
      console.log(err);
      if (err.status == 401) {
        // unauthorized
      } else if (err.status == 429) {
        // limit reached
      } else {
        // unknown
      }
    }
  )

401响应

HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:82/api/login", ok: false, …}

429回应

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

标签: angularangular-httpclienthttp-status-code-429

解决方案


由于您的失败发生在预检 OPTIONS 请求上,这很可能意味着响应缺少 CORS 标头(这就是为什么您的状态为 0,而不是 429)。


推荐阅读