SoFunction
Updated on 2025-04-11

Detailed explanation of http interception in AngularJS

http interception, i.e. $http service allows us to interact with the server, and sometimes we want to do something before we make a request and after we receive a response.
$httpProvider contains an array of interceptors.

We create an interceptor like this.

('myInterceptor', ['$log', function($log){
  $('');
  
  var myInterceptor = {};
  
  return myInterceptor;
}])

Next register interceptor.

(['$httpProvider', function($httpProvider){
  $('myInterceptor');
}])
 

Here are some examples of $http interception.

■ Asynchronous operations in the interceptor

('myInterceotpr','someAsyncServcie', function($q, someAsyncServcie){
  var requestInterceptor = {
    request: function(config){
      var deferred = %();
      ().then(function(){
        ...
        (config);
      }, function(){
        ...
        (config);
      })
      return ;
    }
  };
  
  return requestInterceptor;
})

The above is a request intercepting, which does an asynchronous operation, and updates the config based on the results of the asynchronous operation.

Of course, there are response interceptions.

('myInterceptor',['$q', 'someAsyncService', function($q, someAsyncSercice){
  var responseInterceptor = {
    response: function(response){
      var deferred = $();
      ().then(function(response){
        ...
        (response);
      }, function(response){
        ...
        (response);
      })
      return ;
    }
  };
  return responseInterceptor;
}])

■ Session interception, request interception

There are two types of verification on the server side, one is based on cookies and the other is based on tokens. For token-based authentication, when the user logs in, a token from the server is obtained, which is sent to the server every time it is requested.

Create an injector about session:

('sessionInjector',['SessionService', function(SessionService){
  var sessionInjector = {
    request: function(config){
      if(!){
        ['x-session-token'] = ;
      }
      return config;
    }
  };
  
  return sessionInjector;
}])

It can be seen that the token returned from the server is placed in it.

Register injector:

(['$httpProvider', function($httpProvider){
  $('sessionInjector');
}])

Make a request:

$('');

Before interception, it is roughly:

{
  "transformRequest":[null],
  "transformResponse":[null],
  "method":"GET",
  "url":"",
  "headers":{
    "Accept": "application/json, text/plain,*/*"
  }
}

After intercepting, two additional x-session-token fields are included in the headers:

{
  "transformRequest":[null],
  "transformResponse":[null],
  "method":"GET",
  "url":"",
  "headers":{
    "Accept": "application/json, text/plain,*/*",
    "x-session-token":......
  }
}

■ Timestamp, request and response intercept

('timestampMarker',[function(){
  var timestampMarker = {
    request:function(config){
       = new Date().getTime();
      return config;
    },
    response: function(response){
       = new Date().getTime();
      return config;
    }
  };
  
  return timestampMarker;
}])

The above is intercepted during request and response, and the current time is assigned.

Register the interceptor:

(['$httpProvider', function($httpProvider){
  $('timestampMarker');
}])
 

Then when used, you can calculate the time taken for the request response.

$('').then(function(response){
  var time =  - ;
  ('The time spent on request is ' + time);
})
 



■ Request error recovery, request interception

Simulate an error situation in which a request is intercepted:

('requestRejector',['$q', function($q){
  var requestRejector = {
    request: function(config){
      return $('requestRejector');
    }
  };
  return requestRejector;
}])

Intercept request error:

('requestRecoverer',['$q', function($q){
  var requestRecoverer = {
    requestError: function(rejectReason){
      if(rejectReason === 'requestRejector'){
        //Recovery request        return {
          transformRequest:[],
          transformResponse:[],
          method:'GET',
          url:'',
          headers:{
            Accept:'application/json, text/plain, */*'
          }
        };
      } else {
        return $(rejectReason);
      }
    }
  };
  
  return requestRecoverer;
}])

Register the interceptor:

(['$httpProvider', function($httpProvider){
  $('requestRejector');
  $('requestRecoverer');
}])
 

■ Session error recovery, response interception

('sessionRecoverer',['$q','$injector',function($q, $injector){
 var sessionRecoverer = {
  responseError: function(response){
   //If Session expires   if( == 419){
    var SessionService = $('SessionService');
    var $http = $('$http');
    var deferred = $();
    
    //Create a new session    ().then(, );
    
    return (function(){
     reutrn $http();
    })
   }
   return $(response);
  }
 };
 
 return sessionRecoverer;
}])

The above is all about this article, I hope it will be helpful to everyone's learning.