【问题标题】:How do I get the CORS error which appears on the console, using Angular error handling?如何使用 Angular 错误处理获取控制台上出现的 CORS 错误?
【发布时间】:2019-07-06 10:29:38
【问题描述】:

我已经组装了自己的小错误处理程序来处理 REST 服务器上的 HttpErrorResponses,但我注意到客户端出现问题并且 Angular 将它们包装为传递给我的错误的 HttpErrorResponse 的一部分处理程序。

所以在控制台中,我首先看到的是:

从源访问“http://localhost:8080/group”处的 XMLHttpRequest 'http://localhost:4200' 已被 CORS 策略阻止:值为 响应中的“Access-Control-Allow-Origin”标头不得为 当请求的凭据模式为“包含”时,通配符“*”。这 XMLHttpRequest 发起的请求的凭证模式是 由 withCredentials 属性控制。

在这种情况下这是可以预料的,但我希望我的错误处理程序记录该错误,只是我看不到如何。这是使用时的处理程序:

 getGroups(): Observable<Group[]> {
    return this.http.get<Group[]>(`${this.restUrl}/group`).pipe(
        catchError(
            error => this.errorService.handleError<Group[]>(
                                    error, 'getGroups', [])
          )
      );
  }

和我的错误服务:

  handleError<T>(
      error: HttpErrorResponse,
      operation = 'operation',
      result?: T) {
    this.messageService.add(`${operation} failed`);
    this.messageService.add(`HTTP error response: status[${error.status}];
                error.message:"${error.message}"`);
    this.messageService.add(`Is ErrorEvent? 
                ${error.error instanceof ErrorEvent ? "yes":"no"}`);
    this.messageService.add(`Is ProgressEvent? 
                ${error.error instanceof ProgressEvent ? "yes":"no"}`);

    return of(result as T);
  }

因此,Angular HttpClient 希望只是包装了该错误 - 或完全替换了它。我可以在我的错误处理程序中获取它吗?

我的错误处理程序的输出是:

getGroups failed
HTTP error response: status[0]; error.message:"Http failure response for http://localhost:8080/group: 0 Unknown Error"
Is ErrorEvent? no
Is ProgressEvent? yes

我看不出我能用ProgressEvent做什么。

[2019-02-28] 更新

正如 Anjil 在 cmets 中所说,此 CORS 错误不是 HTTP 错误。它被某物扔到某个地方——我不知道是什么。可能是浏览器,可能是 Angular、RxJS、HttpClient。

【问题讨论】:

  • 我相信 CORS 问题(消息)是由浏览器而不是由 HttpClient 引发的,如果这是您试图在错误处理函数中看到的内容。
  • 通过浏览器 - 是的,我明白了。这是完全有道理的——但是 HttpClient 肯定会得到错误吗?也许它在给出的错误中没有收到任何消息。我还没有尝试过 Sabbir 的解决方案,但希望它会出现。
  • 我不这么认为。它会抛出一个未知的 url 错误或类似的东西。过去,当我不知道 CORS 问题的真正含义时,我也遇到过 CORS 问题。 :D

标签: angular typescript rxjs angular-httpclient


【解决方案1】:

你可以试试下面的代码

getGroups(): Observable<Group[]> {
return this.http.get<Group[]>(`${this.restUrl}/group`).subscribe(
    results => {
      console.log(results)
    },
    err => {
      // Do stuff whith your error
      this.displayError(err);
    },
    () => {
      // Do stuff after completion
    }
  )
}

private displayError(ex): void {
    console.log(ex);
}

【讨论】:

  • OK 不错的尝试,但您的 err 与我的 error 没有任何不同
猜你喜欢
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 2021-09-04
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
相关资源
最近更新 更多