0

I have a problem authenticating a user. In case of problems in the credentials (email and password), I display an error message with a toast. But since this morning, I have the error 401 Unauthorized that appears and so the toast no longer displays error messages. I do not understand where it comes from.

The console's error

POST UrlAPI 401 (Unauthorized)
EXCEPTION: Response with status: 401 Unauthorized for URL: UrlAPI

And this is my POST request

return this.http.post(link, data, options)
    .map((res: Response) => res.json())
    .subscribe((response) => {
            console.log("RESPONSE: ", response);
            if (response.status === 'ok'){
              this.UserData.setSessionId(response.session_id);
              console.log("SESS_ID SAVED", this.UserData.getSessionId());
              this.nav.setRoot(TabsPage);
             }
            else {
              let toast = this.toastCtrl.create( {
                  message: response.errors,
                  duration: 3000,
                  position: 'top'
              });
            toast.present();
          }
        });

Reponse Headers

Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:Keep-Alive
Content-Length:57
Content-Type:application/json
Date:Tue, 23 May 2017 13:49:56 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.10 (Debian)

Request Headers

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:16
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host: UrlAPI
Origin:http://localhost:8101
Referer:http://localhost:8101/?ionicplatform=ios&ionicstatusbarpadding=true
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36

1 Answers1

0

The problem is that the Angular Http service throws an error when a status code other than 2xx is returned from the server or if the server times out.

This is dealt with by inserting an observable catch between the .map and .subscribe, OR by adding a second parameter to the subscribe, which is an error handler.

Solution 1

.map( ... )
.catch( /* handle error here */ )
.subscribe( ... )

Solution 2

.map( ... )
.subscribe( 
    (response) => { ... },
    (error) => { /*handle error here */ }
)

See this similar question for an example: How to deal with http status codes other than 200 in Angular 2