chrome中完整的HTTP拦截器错误响应

时间:2018-08-16 18:11:23

标签: javascript angular angular5

在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

2 个答案:

答案 0 :(得分:6)

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

我仍然很困惑IE如何响应此错误。

答案 1 :(得分:0)

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

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

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

这是一篇有关拦截器和用法的相当新的中型文章,可能会澄清一些问题 https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

希望这会有所帮助

相关问题