How can I send request again in response intercept

2020-05-14 07:44发布

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条回答
▲ chillily
2楼-- · 2020-05-14 08:18

You're on the right path, you basically store the request in a queue and retry it after you've re-established the session.

Check out this popular module: angular http auth (https://github.com/witoldsz/angular-http-auth). In this module, they intercept 401 responses but you can model your solution off of this approach.

查看更多
贪生不怕死
3楼-- · 2020-05-14 08:25

The responseError method of httpInterceptor have to be like this:

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

And the magic happens here:

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);
}
查看更多
你好瞎i
4楼-- · 2020-05-14 08:31

Here is my solution using promises for those interested. Basically you need to request a new session, and wait for the response before sending a new request corresponding to the original request (using response.config). By returning the promise $http(response.config) you ensure that the response will be treated as if it was the original request.
(syntax may not be the best as I'm new to promises)

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');
    });
查看更多
霸刀☆藐视天下
5楼-- · 2020-05-14 08:37

More or less the same solution, translated in typescript:

/// <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)
    }]);

Hope this help.

查看更多
登录 后发表回答