$http Interceptors

Introduction

AngularJS interceptors offer a convenient way to modify request made by the $http service both before they are sent and after they return.

Setup

function testInterceptor() {
  return {
    request: function(config) {
      return config;
    },

    requestError: function(config) {
      return config;
    },

    response: function(res) {
      return res;
    },

    responseError: function(res) {
      return res;
    }
  }
}

angular.module('app', [])
.factory('testInterceptor', testInterceptor)
.config(function($httpProvider) {
  $httpProvider.interceptors.push('testInterceptor');
})
.run(function($http) {
  $http.get('http://test-routes.herokuapp.com/test/hello')
    .then(function(res) {
      console.log(res.data.message)
    })
})
<html>
    <head>
        <title>$http interceptors</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
        <script src="app.js"></script>
    </head>
    <body ng-app="app">
    </body>
</html>

An interceptor is simply a factory() service that returns an object with 4 properties that map to functions:

  • request: called before a request is sent, capable of mutating the request object
  • requestError:
  • response: called with an $http request succeeds, is passed the results object,
  • responseError: called if an $http method fails

This object is then registered as an interceptor with the $httpProvider in a config() block. It's perfectly fine to include all or only a subset of the properties that are needed.

The way to think about interceptor functions is as promise callback functions that are called for all HTTP requests.

An Example: Automatically Adding CSRF Tokens

To demonstrate a useful task for interceptors, let's use the request property to automatically add a csrf token to every request made to the domain test-routes.herokuapp.com. These tokens are commonly used by frameworks such as Ruby on Rails and Django:

request: function(config) {
  if(config.url.indexOf('http://test-routes.herokuapp.com') > -1) {
    config.headers['x-csrf-token'] = 'lalalalala';
  }
  return config;
}

Here we're testing the url of the request to see if it matches the URL we want. Then, we're attaching an extra header that contains (what would be) the CSRF token.

Another really useful feature of interceptors is dealing with authentication of requests. You can see an example of this here: Simple AngularJS Authentication with JWT