Raj Goli
Raj Goli

Reputation: 23

AngularJS Error Code 401 handling without interceptors?

Following is the code I use, I get the Authentication Success Alert if the basic auth succeeds but the else alert "Authentication failed" is never displayed when the credentials are wrong. I do not use any routes and I don't have a need to use interceptors. Is there a way to get the 401 errors without using interceptors?

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

In Controller:

$scope.Login = function() {

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

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

};

Upvotes: 1

Views: 1304

Answers (1)

Jay Regal
Jay Regal

Reputation: 3273

As described in the AngularJS documentation for $http, the $http call returns a promise with an error method, which has the code(number) of the status as one of it's parameters. You can check for a 401 status in there:

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

Upvotes: 2

Related Questions