Angular5 http响应拦截器无法读取状态码

时间:2017-12-16 05:49:14

标签: angular response observable interceptor http-status-code-401

我试图拦截http响应并重定向任何401,但下面的错误对象只返回以下字符串。我期待至少找到状态代码..

  

401 - 未经授权的详细信息:Http失败响应   http://localhost:4200/api/foo:401未经授权

我可以在网络选项卡中看到服务器正在返回格式良好的401。关于如何正确阅读它们的任何想法?

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authRequest = request.clone({
        setHeaders: {
            Authorization: `Bearer ${this.authService.getToken() || ''}`
        }
    });

    return next.handle(authRequest).do(event => { }, err => {
        if (err instanceof HttpErrorResponse && err.status === 401) {
            this.authService.handleAuthentication();
        }
    });
}

编辑:我刚刚注意到,如果我关闭Web服务器以强制504网关超时,我会将错误视为一个完整的字符串,而且没有错误代码。

  

504 - 网关超时详细信息:Http失败响应   http://localhost:4200/api/foo:504网关超时

4 个答案:

答案 0 :(得分:1)

尝试使用catch

return next
    .handle(authReq)
    .do(event => {
        if (event instanceof HttpResponse) {
            /* Make your code here */
        }
    })
    .catch((err) => {
        if (err.status === 401 && err.statusText === 'Unauthorized') {


        }
        return Observable.throw(err);
    });

答案 1 :(得分:1)

通过执行以下操作,我能够在Angular 5中正确运行我的Auth Interceptor:

auth.interceptor.ts

import { Injectable } from '@angular/core';
import {
    HttpErrorResponse,
    HttpEvent,
    HttpHandler,
    HttpInterceptor, 
    HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
      private authService: AuthService
  ) { }

  public intercept(
      req: HttpRequest<any>,
      next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    return this.authService.getToken().flatMap((token: string) => {
      return next.handle(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
    }).do(() => { }, (error: any) => {
      if (error instanceof HttpErrorResponse && (error as HttpErrorResponse).status === 401) {
        this.authService.login();
      }
    });
  }
}

答案 2 :(得分:0)

好的,这里的问题是我有一个预先存在的错误拦截器,它在我的401拦截器之前修改了响应。这家伙正在整理所有东西。感谢上述所有回复。

答案 3 :(得分:0)

对于Angular 6,请看这篇文章:
HttpClient Interceptor forces request duplicates

相关问题