32

I've made an interceptor in my application that detects session loss (server sends an HTTP 419). In this case, I need to request a new session from the server, and then I would like to send the original request again automatically.
Maybe I could save the request in a request interceptor, and then send it again, but there might be a simpler solution.

Note that I have to use a specific webservice to create the session.

angular.module('myapp', [ 'ngResource' ]).factory(
    'MyInterceptor', 
    function ($q, $rootScope) {
        return function (promise) {
            return promise.then(function (response) {
                // do something on success
                return response;
            }, function (response) {
                if(response.status == 419){
                    // session lost
                    // create new session server-side
                    // Session.query();
                    // then send current request again
                    // ???
                }
                return $q.reject(response);
            });
        };
    }).config(function ($httpProvider) {
        $httpProvider.responseInterceptors.push('MyInterceptor');
    });
4

4 回答 4

21

这是我为感兴趣的人使用承诺的解决方案。基本上您需要请求一个新会话,并在发送与原始请求相对应的新请求之前等待响应(使用 response.config)。通过返回承诺 $http(response.config) 您确保响应将被视为原始请求。
(语法可能不是最好的,因为我是新的承诺)

angular.module('myapp', [ 'ngResource' ]).factory(
    'MyInterceptor', 
    function ($q, $rootScope) {
        return function (promise) {
            return promise.then(function (response) {
                // do something on success
                return response;
            }, function (response) {
                if(response.status == 419){
                    // session lost
                    var Session = $injector.get('Session');
                    var $http = $injector.get('$http');
                    // first create new session server-side
                    var defer = $q.defer();
                    var promiseSession = defer.promise; 
                    Session.query({},function(){
                        defer.resolve();
                    }, function(){
                       // error
                       defer.reject();
                    });       
                    // and chain request
                    var promiseUpdate = promiseSession.then(function(){
                        return $http(response.config);
                    });
                    return promiseUpdate;
                }
                return $q.reject(response);
            });
        };
    }).config(function ($httpProvider) {
        $httpProvider.responseInterceptors.push('MyInterceptor');
    });
于 2013-09-06T09:27:29.207 回答
20

responseError方法httpInterceptor必须是这样的:

responseError: function (response) {
  // omit the retry if the request is made to a template or other url
  if (response.config.apiCal === true) {
    if (response.status === 419) {
      var deferred = $q.defer();
      // do something async: try to login.. rescue a token.. etc.
      asyncFuncionToRecoverFrom419(funcion(){
        // on success retry the http request
        retryHttpRequest(response.config, deferred);
      });
      return deferred.promise;
    } else {
      // a template file...
      return response;
    }
  }
}

魔法发生在这里:

function retryHttpRequest(config, deferred){
  function successCallback(response){
    deferred.resolve(response);
  }
  function errorCallback(response){
    deferred.reject(response);
  }
  var $http = $injector.get('$http');
  $http(config).then(successCallback, errorCallback);
}
于 2015-03-26T05:55:08.000 回答
6

您走在正确的道路上,您基本上将请求存储在队列中,并在重新建立会话后重试。

查看这个流行的模块:angular http auth ( https://github.com/witoldsz/angular-http-auth )。在此模块中,它们拦截 401 响应,但您可以根据此方法对您的解决方案进行建模。

于 2013-09-05T13:59:19.473 回答
5

或多或少相同的解决方案,用打字稿翻译:

/// <reference path="../app.ts" />
/// <reference path="../../scripts/typings/angularjs/angular.d.ts" />

class AuthInterceptorService {

    static serviceId: string = "authInterceptorService";

    constructor(private $q: ng.IQService, private $location: ng.ILocationService, private $injector, private $log: ng.ILogService, private authStatusService) {}

    // Attenzione. Per qualche strano motivo qui va usata la sintassi lambda perché se no ts sbrocca il this.
    public request = (config: ng.IRequestConfig) => {

        config.headers = config.headers || {};

        var s: AuthStatus = this.authStatusService.status;
        if (s.isAuth) {
            config.headers.Authorization = 'Bearer ' + s.accessToken;
        }

        return config;
    }

    public responseError = (rejection: ng.IHttpPromiseCallbackArg<any>) => {

        if (rejection.status === 401) {

            var that = this;

            this.$log.warn("[AuthInterceptorService.responseError()]: not authorized request [401]. Now I try now to refresh the token.");

            var authService: AuthService = this.$injector.get("authService");
            var $http: ng.IHttpService = this.$injector.get("$http");

            var defer = this.$q.defer();
            var promise: ng.IPromise<any> = defer.promise.then(() => $http(rejection.config));

            authService
                .refreshAccessToken()
                    .then((response) => {

                        that.$log.info("[AuthInterceptorService.responseError()]: token refreshed succesfully. Now I resend the original request.");

                        defer.resolve();
                    },
                    (err) => {

                        that.$log.warn("[AuthInterceptorService.responseError()]: token refresh failed. I need to logout, sorry...");

                        this.authStatusService.clear();
                        this.$location.path('/login');
                    });

            return promise;
        }

        return this.$q.reject(rejection);
    }
}

// Update the app variable name to be that of your module variable
app.factory(AuthInterceptorService.serviceId,
    ["$q", "$location", "$injector", "$log", "authStatusService", ($q, $location, $injector, $log, authStatusService) => { 
        return new AuthInterceptorService($q, $location, $injector, $log, authStatusService)
    }]);

希望这有帮助。

于 2015-02-04T12:53:35.980 回答