【问题标题】:AngularJS Error Code 401 handling without interceptors?没有拦截器的AngularJS错误代码401处理?
【发布时间】:2015-02-28 18:21:53
【问题描述】:

以下是我使用的代码,如果基本身份验证成功,我会收到身份验证成功警报,但是当凭据错误时,永远不会显示 else 警报“身份验证失败”。我不使用任何路线,也不需要使用拦截器。有没有办法在不使用拦截器的情况下获得 401 错误?

this.authorize = function(request, callbackFunc) {
  var encodedString = btoa(request.userName + ":" + request.password);
  var basicAuthString = 'Basic ' + encodedString;
  var requestObject = {
    location: '40005'
  };
  var req = {
    method: this.method,
    crossDomain: true,
    url: this.loginURL,
    data: requestObject,
    headers: {
      'Authorization': basicAuthString,
      'Content-Type': 'application/json',
      'Accept': '*/*',
      'apiKey': ''
    }

  };

  $http(req)
    .success(function(response) {
      callbackFunc(response, "success");
    })
    .error(function(response) {
      console.log("Error Received");
      callbackFunc(response, "error");
    });
};

在控制器中:

$scope.Login = function() {

  AuthenticationService.authorize($scope.LoginRequest, function(response, responseCode) {
    if (responseCode === "success") {

      alert("Authentication Success");
    } else {
      alert("Authentication Failed");
    }
  });

};

【问题讨论】:

  • console.log("Error Received"); 打印出来了
  • 不。它也不去那里。
  • 你的意思是说服务内部的错误函数不会触发?
  • 看这里我可以做同样的事情不会失败plnkr.co/edit/RlUTqN?p=preview正确显示“错误”消息
  • 我也尝试过添加拦截器

标签: angularjs angular-http angular-http-interceptors angular-http-auth


【解决方案1】:

AngularJS documentation for $http 中所述,$http 调用返回一个带有错误方法的承诺,该方法将状态的代码(数字)作为其参数之一。您可以在那里检查 401 状态:

error(function(data, status, headers, config) {
    if(status === 401){
        // Add your code here
    }
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 2018-04-25
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多