简体   繁体   English

无法在Angular 7 HTTP拦截器中捕获401状态代码

[英]Not able to catch 401 status code in Angular 7 HTTP Interceptor

I am using Angular 7 and I have used HTTP Interceptor in my application. 我正在使用Angular 7,并且在我的应用程序中使用了HTTP Interceptor。

I am not able to track 401 status code in that HTTP Interceptor. 我无法在该HTTP拦截器中跟踪401状态代码。

I tried pitting catchError and tap but it gives status 0 , I want 401. 我尝试使catchErrortap它的状态为0 ,我想要401。

My code is here: 我的代码在这里:

return next.handle(request).pipe(tap(event => {
            console.log('the ev is :', event);
            if (event instanceof HttpResponse) {
                this.onEnd();
            }
         }, err => {
            if (err instanceof HttpErrorResponse) {
                console.log('the eeeeeee is :', err);
                this.onEnd();
                // User logged out
                if (err.status === 401) {
                    this.router.navigate(['logout']);
                }
            }
        })).pipe(catchError(error => {
            console.log('the ee is :', error);
            return Observable.throw(error);
        }));

Thanks. 谢谢。

I'm using angular 6 and this redirects to the login page when there's an error 401 or 403. I think it should work in angular 7. There should be other ways to do it but I share what works for me in this case. 我使用的是角度6,当出现错误401或403时,它将重定向到登录页面。我认为它应该在角度7中起作用。应该有其他方法可以做到这一点,但在这种情况下,我会分享对我有用的方法。 Hope it helps. 希望能帮助到你。

intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError(
        err =>
          new Observable<HttpEvent<any>>(observer => {
            if (err instanceof HttpErrorResponse) {
              const errResp = <HttpErrorResponse>err;
              if (errResp.status === UNAUTHORIZED || err.status === FORBIDDEN) {
                this.authService.goToLogin(this.router.url);
              }
            }
            observer.error(err);
            observer.complete();
          })
      )
    );

} }

Maybe someone can suggest me what's the better way to carry out this kind of stuff. 也许有人可以建议我,开展这种工作的更好方法是什么。

You have an error handler in the tap method and then a separately piped catchError . tap方法中有一个错误处理程序,然后是一个单独的管道catchError Unless you intend to act on the received response ie http 200. A simple interceptor implementation would be: 除非您打算对收到的响应(即http 200)采取行动,否则简单的拦截器实现将是:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  return next.handle(request).pipe(
      catchError(err => {
        if (err instanceof HttpErrorResponse) {

          if (err.status === 401 || err.status === 403) {
              // Invalidate user session and redirect to login/home
          }

          // return the error back to the caller
          return throwError(err);
        }
      }),
      finalize(() => {
        // any cleanup or final activities
      })
    );
}

Try this 尝试这个

@Injectable()
export class HTTPListener implements HttpInterceptor {
constructor(private status: HTTPStatus) {
}



intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(map(event => {
        return event;
    }), catchError(err => {
        if (err.status === 401) {
        }

        const error = err.error.message || err.statusText;
        return throwError(error);
    }),
        finalize(() => {
        })
    )
}
}
import { Injectable } from '@angular/core';
import { 
 HttpEvent, HttpRequest, HttpHandler, 
      HttpInterceptor, HttpErrorResponse 
    } from '@angular/common/http';
    import { Router } from '@angular/router';
    import { Observable, of } from 'rxjs';
    import { catchError } from 'rxjs/operators';

    @Injectable()
    export class ServerErrorInterceptor implements HttpInterceptor {
    constructor(public router: Router){

    }
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).pipe(
          catchError((error: any) => {
            if (error.status == 401 || error.status == 0) {
                this.router.navigate(['/']);
            } else {

            }
            return of(error);
          })
        );    
      }
    }
     providers: [
        {
                provide: HTTP_INTERCEPTORS,
                useClass: ServerErrorInterceptor,
                multi: true
            }
      ],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 Angular HttpInterceptor 捕获 401 状态代码 - Unable to catch 401 status code with Angular HttpInterceptor 预检的响应具有无效的HTTP状态代码:401 angular - Response for preflight has invalid HTTP status code: 401 angular Angular JS Interceptor处理HTTP错误状态 - Angular JS Interceptor to handle HTTP Error status angularjs 拦截器:为什么它没有在 $http 拦截器中接收到正确的状态代码和消息 - angularjs Interceptor:why is it not receiving the proper status code and message in $http interceptor Angular:如何捕获失败的 http.get() 方法的 Http 状态码 - Angular: How to catch Http Status Code of a failed http.get() method Angular 5 http拦截器不拦截 - Angular 5 http interceptor not intercepting 飞行前的响应具有无效的HTTP状态代码401-测试 - Response for preflight has invalid HTTP status code 401 - Testing XMLHttpRequest无法加载URL无效的HTTP状态代码401 AngularJs - XMLHttpRequest cannot load URL Invalid HTTP status code 401 AngularJs 使用ajaxError全局处理程序显示HTTP状态代码401详细信息 - Using ajaxError global handler to display HTTP status code 401 details HTTP拦截器中的角度HTTP - Angular HTTP within a HTTP Interceptor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM