Search code examples
angularangular-routerangular-guards

how to make angular response to http 401


I'm having a nodejs (express) as a server side and an angular 6 as client.In the server I have middlewear function that makes a session check. In case where the session is invalid or not exists, I would like to send a response to the client so that it can react to it. I thought of returning a response code of 401 from the server, and make some kind of listener\route-guard\HttpInterceptor in the client, so - it can manage the situation in the client (redirect it to the login page, for example). Here is my code in the server:

router.use('/', (req, res, next) =>
{
    if (!req.session.user)
    {
        res.status(401);
    }
    else{
        next();
    }
})

How can I catch\listen to this response in the angular app ?


Solution

  • You can create an HttpInterceptor in which you can check wether status is 401, if yes then logout user and redirect to login page. What HttpInterceptor do is intercept every request and response and allow you to do some specific action like checking if servce returned 401 status. However be aware of range for interceptor it's working like services so if you include it in your top level module then it will intercept every request and response

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
        constructor( 
           private authService: AuthService
        ) { }
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            return next.handle(request).pipe(
                map((event: HttpEvent<any>) => event), // pass further respone
                catchError((error: HttpErrorResponse) => {
                    // here will be catched error from response, just check if its 401
                    if (error && error.status == 401)
                        // then logout e.g. this.authService.logout()
                    return throwError(error);
                }));
        }
    }
    

    And then include it in app.httpmodule in providers section

    providers: [
      {
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
      },
    ]
    

    Read more at angular.io docs or angular.io guide