401 Ionic 2中的POST请求未经授权的错误?

时间:2017-05-25 10:31:21

标签: angularjs ionic2 http-post ionic3

我在验证用户时遇到问题。如果凭据(电子邮件和密码)出现问题,我会显示带有Toast的错误消息。但是从今天早上开始,我出现错误401 Unauthorized,因此toast不再显示错误消息。我不明白它的来源。

控制台的错误

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

这是我的POST请求

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

回复标题

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)

请求标题

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 个答案:

答案 0 :(得分:0)

问题是,当从服务器返回2xx以外的状态代码或服务器超时时,Angular Http服务会抛出错误。

通过在.map和.subscribe之间插入一个observable catch来处理,或者通过向subscribe添加第二个参数来处理它,这是一个错误处理程序。

解决方案1 ​​

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

解决方案2

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

有关示例,请参阅此类似问题How to deal with http status codes other than 200 in Angular 2