【问题标题】:Http interceptor Error Response in complete in chromeHttp拦截器错误响应在chrome中完成
【发布时间】:2019-01-23 18:25:37
【问题描述】:

我在使用 Angular 5 中的 httpinterceptor 时遇到了奇怪的问题。我无法在 Chrome 中获得错误响应和错误状态代码,但能够在下面的 IE 中获得我的 HttpInterceptor 代码。

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } 
from '@angular/common/http';
import { finalize, tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const startTime = Date.now();
let status: string;

return next.handle(req).pipe(
    tap(
      event => {
        status = '';
        if (event instanceof HttpResponse) {
          status = 'succeeded';
        }
      },
      error => {
        if(error instanceof HttpErrorResponse)  {
          console.log(error.error.message) 
          // Above message is printing in IE but no in chorme.
       }
     }
    ),
    finalize(() => {

    })
);
 }

} 

在上面的错误中,我可以在 IE 中看到但在 Chrome 中看不到的消息和状态代码。请帮助我如何解决这个问题。

编辑: 我正在使用来自不同来源的数据,并且在 Web 服务中启用了 cors

【问题讨论】:

  • 你试过了吗:if(error instanceof HttpErrorResponse || error instanceof ErrorEvent)?或者只是不进行类型检查,看看 chrome 是否完全达到错误?
  • 您测试的实际 HTTP 错误是什么? Chrome 中是否抛出了 HTTP 错误?
  • 我正在尝试使用服务引发的一些自定义消息来处理 500 内部服务器错误
  • 这是 COR 请求还是同源请求?
  • 这是一个 CORS 请求

标签: javascript angular angular5


【解决方案1】:

我发现了问题,这是由于没有在服务器端设置错误的响应标头。服务器直接针对错误抛出异常,而不设置响应标头。我已经在服务器端设置了响应头,现在我可以在 chrome 中看到错误消息。

我仍然很困惑 IE 是如何响应这个错误的。

【讨论】:

    【解决方案2】:

    您缺少 HttpErrorResponse 导入,一种更与浏览器无关的方法是查看错误状态,而不是错误消息。

      if (err instanceof HttpErrorResponse) {
          console.log(err.status);
      }
    

    我相信 IE 使用其他浏览器不使用的友好错误消息 https://blogs.msdn.microsoft.com/ieinternals/2010/08/18/friendly-http-error-pages/

    这是一篇关于拦截器和用法的相当最新的 Medium 文章,它可能会澄清一些事情 https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

    希望对你有帮助

    【讨论】:

    • 使用错误的 CORS 标头,Chrome 会返回错误代码“0”,但它不应该...因此这并不是问题的完全解决方案。
    • Grant 在这里发布之前实施了同样的方法,但没有运气
    • 马丁你是对的,这是由于错误的标题
    猜你喜欢
    • 2019-03-11
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多