【问题标题】:401 Unauthorized error for POST request in Ionic 2?Ionic 2 中的 POST 请求出现 401 未经授权的错误?
【发布时间】:2017-05-25 10:31:20
【问题描述】:

我在验证用户时遇到问题。如果凭据(电子邮件和密码)出现问题,我会显示一条带有 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

【问题讨论】:

    标签: angularjs ionic2 http-post ionic3


    【解决方案1】:

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

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

    解决方案 1

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

    解决方案 2

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

    有关示例,请参阅 this similar questionHow to deal with http status codes other than 200 in Angular 2

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      相关资源
      最近更新 更多