Angular5 http reponse interceptor unable to read status code

岁酱吖の 提交于 2019-12-23 03:01:44

问题


I am trying to intercept http responses and redirect any 401's but the err object below is only returning me the following string. I was expecting to at least find the status code..

401 - Unauthorized Details: Http failure response for http://localhost:4200/api/foo: 401 Unauthorized

I can see in the network tab that a well formed 401 is being returned by the server. Any ideas on how I can read them correctly?

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();
        }
    });
}

Edit: I have just noticed that if i switch off the web server to force a 504 gateway timeout I get the error as a complete string without an error code as well.

504 - Gateway Timeout Details: Http failure response for http://localhost:4200/api/foo: 504 Gateway Timeout


回答1:


try to use 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);
    });



回答2:


I was able to get my Auth Interceptor functioning correctly in Angular 5 by doing the following:

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();
      }
    });
  }
}



回答3:


Ok so the problem here was I had a pre-existing error interceptor that was modifying the response before my 401 interceptor. This guy was stringifying everything. Thanks to all the above responses.




回答4:


For Angular 6, look at this post:
HttpClient Interceptor forces request duplicates



来源:https://stackoverflow.com/questions/47842939/angular5-http-reponse-interceptor-unable-to-read-status-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!