获取响应代码401会导致跳过代码块

问题描述 投票:0回答:1

我正在写一个离子v1 /​​ express / mongo / node app。在检查用户是否经过身份验证时,我有以下代码:

checkAuthentication: function(token) {
            console.log(token);
            return $http.get("http://validUrl/test", {
                headers: {
                    'testingAuth': token
                }
            }).then(function(result) {
                return result.data;
            });
        }

我这样称呼它:

checkAuthentication(token).then(function(response) {
            console.log("testing response: " + response);
            // if a valid token is already in storage = response contains "Success"(?), just $state.go to main page, else call the login() function
            if (response.content === "Success") {
                // $state.go main page
            } else {
                console.log("could not log in");
            }
        })

问题是,当我从服务器返回代码401时,我以某种方式跳过checkAuthentication函数中的then块。执行不会在“return result.data”或“console.log(”无法记录“)的断点处停止。

我做错了什么吗?我是否需要做些什么才能强行进入该区块?谢谢你的建议。

angularjs authentication response skip
1个回答
0
投票

问题在于您的错误处理!我冒昧地修改你的代码以及进行$ http调用的方式。这是工作的plunker相同。

如果你观察了$scope.login()函数,我已经注入了服务对象并调用了执行HTTP调用的checkAuthentication()函数。当你使用.then进行http调用时,angular提供了使用两个函数进行成功和错误回调的问题,其中你的HTTP错误是当HTTP调用失败时。

这是角度doc相同。

在您的示例中,您没有错误回调方法,因此它不会进入您的if else条件。

var app = angular.module("App", []);
app.controller('AppCtrl', ['$rootScope', '$scope', '$http', 'Service', function($rootScope, $scope, $http, Service) {


  $scope.login = function(token) {
  //call the injected service in the function for HTTP call..
    Service.checkAuthentication(token).then(function(response) {
      console.log("testing response: " + response);
      // if a valid token is already in storage = response contains "Success"(?), just $state.go to main page, else call the login() function
      if (response.content === "Success") {
        // $state.go main page
      } 
    },function(error){
      console.log(error);
      console.log("could not log in due to error...");
    });
  };


}]);
//use angular services to do a http call for better code maintainability...
app.service('Service', ['$http', '$rootScope', function($http, $rootScope) {

  return {
    checkAuthentication: function(token) {
      return $http.get("http://validUrl/test", {
        headers: {
          'testingAuth': token
        }
      });
    }
  };
}]);
© www.soinside.com 2019 - 2024. All rights reserved.