如果 angularjs 中的状态代码为 403,请注销

Log out if status code is 403 in angularjs

本文关键字:注销 代码 angularjs 状态 如果      更新时间:2023-09-26

我有一个SPA(单页应用程序),它向服务器发送大量http请求,服务器检查发送请求的用户是否经过身份验证。

如果用户未通过身份验证,我会将他重定向到如下所示的登录页面:

$scope.getGroups = function () {
    $http({
        method: "get",
        url: "/enterprises/groups"
    }).success(function (response) {
        GroupService.updateGroups(response.groups);
    }).error(function (errResponse, status) {
        if(status == 403){
            $location.path("login")
        }
    });
};

问题是我有很多http请求,我不想每次都处理"禁止"异常。

有没有办法编写这种代码,比如说,配置并在任何地方应用它?

您可以创建一个服务来处理此问题,并将其添加到$http拦截器中。作为如下服务:

app.factory('authInterceptorService', ['$q','$location', function ($q, $location){
    var responseError = function (rejection) {
        if (rejection.status === 403) {
            $location.path('login');
        }
        return $q.reject(rejection);
    };
    return {
        responseError: responseError
    };
}]);

然后将其添加到 in config

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptorService');
}]);

然后,这将适用于提出的所有请求。

我最近在自己的应用程序中遇到了需要相同的操作,最终在$httpProvider上使用了拦截器。这种事情:

angular.module('notesApp', [])
  .controller('MainCtrl', ['$http', function($http) {
    ...
  }]).factory('MyLoggingInterceptor', ['$q', function($q) {
    return {
      request: function(config) {
        console.log('Request made with ', config);
        return config;
        // If an error, or not allowed, or my custom condition
        // return $q.reject('Not allowed');
      },
      requestError: function(rejection) {
        console.log('Request error due to ', rejection);
        // Continue to ensure that the next promise chain
        // sees an error
        return $q.reject(rejection);
        // Or handled successfully?
        // return someValue;
      },
      response: function(response) {
        console.log('Response from server', response);
        // Return a promise
        return response || $q.when(response);
      },
      responseError: function(rejection) {
        console.log('Error in response ', rejection);
        // Continue to ensure that the next promise chain
        // sees an error
        // Can check auth status code here if need to
        // if (rejection.status === 403) {
        //   Show a login dialog
        //   return a value to tell controllers it has
        // been handled
        // }
        // Or return a rejection to continue the
        // promise failure chain
        return $q.reject(rejection);
      }
    };
  }])
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('MyLoggingInterceptor');
  }]);