Capture HTTP 401 with Angular.js interceptor Capture HTTP 401 with Angular.js interceptor angularjs angularjs

Capture HTTP 401 with Angular.js interceptor


For AngularJS >1.3 use $httpProvider.interceptors.push('myHttpInterceptor');

.service('authInterceptor', function($q) {    var service = this;    service.responseError = function(response) {        if (response.status == 401){            window.location = "/login";        }        return $q.reject(response);    };}).config(['$httpProvider', function($httpProvider) {    $httpProvider.interceptors.push('authInterceptor');}])


in app config block:

var interceptor = ['$rootScope', '$q', "Base64", function(scope, $q, Base64) {  function success(response) {    return response;  }  function error(response) {    var status = response.status;    if (status == 401) {      //AuthFactory.clearUser();      window.location = "/account/login?redirectUrl=" + Base64.encode(document.URL);      return;    }    // otherwise    return $q.reject(response);  }  return function(promise) {    return promise.then(success, error);  }}];


I don't know why, but response with 401 error goes into success function.

'responseError': function(rejection)                {                    // do something on error                    if (rejection.status == 401)                    {                        $rootScope.signOut();                    }                    return $q.reject(rejection);                },                'response': function (response) {                    // do something on error                    if (response.status == 401) {                        $rootScope.signOut();                    };                    return response || $q.when(response);                }