2

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 ?

Guy E
  • 1,775
  • 2
  • 27
  • 55
  • Do you have any code of the request from your client? – qvpham Jun 19 '19 at 09:06
  • Although you use Angular, this has nothing to do with, so I removed the tags. Consider adding tags such as [tag:node] or [tag:express]. –  Jun 19 '19 at 09:07
  • 1
    @Maryannah, he asked "How can I catch\listen to this response in the angular app ?" I believe he is asking an angular-related question. – terahertz Jun 19 '19 at 09:09
  • @Riv my bad, I focused on `I would like to send a response to the client so that it can react to it`. I'm adding the tags back, and your solution is [here](https://angular.io/guide/router#canactivate-requiring-authentication) –  Jun 19 '19 at 09:12
  • If you are talking about a 401 HTTP error then I suppose you would like to redirect your user to the login page if any of its requests are throwing a 401. If it is the case I would suggest you to take a look at the HttpInterceptor interface & of course at the RxJS catchError – Geoffrey Migliacci Jun 19 '19 at 09:13
  • I've done something very similar here. You might to check it and get the idea [ErrorInterceptor](https://github.com/lealceldeiro/gms/blob/master/client/src/app/core/interceptor/error.interceptor.ts#L13) – lealceldeiro Jun 19 '19 at 09:18

2 Answers2

5

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

Patryk Brejdak
  • 1,571
  • 14
  • 26
2

There are two parameters present when you hit http calls . First : the success callback . Second : the error callback.

for example if we have a service named api below will be the complete code :

if you need to capture the error in service:

 getData(){ 
  this._http.get(url).map((response: Response) =>{
     return response.json();    
   })
     .catch(this.handelError) 
}

handelError(error: Response){
   console.log('got below error from server',error);
}

If you need to capture error in component:

 someMethod(){

    this._apiService.getData().susbscribe((result)=>{
         console.log('sucess',result);
        // do further processing
    },(error)=>{
        console.log('error from service',error);
        // do further processing
     });
}
programoholic
  • 4,830
  • 5
  • 20
  • 59
  • This is the basic methodology and behavior - I was looking for a solution with one point of treatment - this is due to the fact that it is related to a http 401 (unauthorize) error which is relevant to every request to the server. See Patryk Brejdak answer - it is perfect – Guy E Jun 19 '19 at 10:57
  • @Guy E it was difficult to understand what you want exactly by looking at the amount of information you have provided in the question. However glad that your problem is solved. – programoholic Jun 19 '19 at 11:43