In a request and response communication of a HTTP call if we want to inject some custom logic the HTTP Interceptor comes into picture. HTTP Interceptors executes some custom logic before or after the HTTP call.
For example, appending the authentication token to every HTTP request and that token is generated from the client who needs to be validated at the server for security purpose.
These interceptors act as a hook up for the HTTP calls.
HTTP Interceptors are used for adding custom logic for authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching, adding custom header, timestamp in the request /response, encrypt and decrypt the request and response information or manipulate the request and response data over the request cycles.
HTTP Interceptors are similar to custom HTTP Module of ASP.NET.
There are four kinds of interceptors in AngularJS - Request, requestError, response, responseError
Syntax for creating Http Interceptors
- var Interceptor = function ($q)
- {
- return {
- request: function (config)
- {
- return config;
- },
- requestError: function (rejection)
- {
- return $q.reject(rejection);
- },
- response: function (result)
- {
- return result;
- },
- responseError: function (response)
- {
- return $q.reject(response);
- }
- }
- }
- interceptorApp = angular.module('interceptorApp', []).config(function ($httpProvider)
- {
- $httpProvider.interceptors.push(testInterceptor);
- });
Let us see what these interceptors
are and how they are used.
Request
This interceptor is called before $http sends the request to the server. This function takes the request configuration object as input parameter and returns a configuration object.
When there is need of adding, modifying or removing data prior to sending to the server for each request the request functions of the interceptors are used.
For example,
Let us consider we want to insert the authentication token to each request.
- request: function (config) {
- console.log('request started...');
-
- var token = $cookieStore.get("auth");
- config.headers['x-csrf-token'] = token;
- return config;
- }
requestError
This interceptor gets called when a request interceptor threw an error or resolved with a rejection code.
For example,
Let us say some error has happened when request interceptors fail and it has blocked the HTTP call, and then log the rejection.
- requestError: function (rejection) {
- console.log(rejection);
-
- return $q.reject(rejection);
- }
Response
This interceptor is called when the $http receives the response from the server.
This function receives a response object as a parameter return a response object or a promise. A response interceptor is used to modify the response data or adding a new set of values, calling another module or services call.
For example,
Let us consider the response which we have got from the service we need to manipulate and add some keys to the result.
- response: function (result) {
- console.log('data for ' + result.data.name + ' received');
-
-
- console.log('request completed');
- return result;
- },
Here result["testKey"] = 'testValue' is added to the result object to the UI Page.
responseError
There are some situations where one call has failed and the application need to trigger some action based on different HTTP status code. This interceptor receives a response object as a parameter return a response object or a promise. The application level generic error handling is achieved by using this interceptor.
For example,
Let us consider the situation of calling the HTTP service call has failed we need to show some error page or login page checking HTTP status code returned from the server.
- responseError: function (response) {
- console.log('response error started...');
-
-
- if (response.status === 401) {
- $location.path('/signin')
- $rootScope.$broadcast('error')
- }
-
- if (response.status === 500) {
- $rootScope.ErrorMsg = "An Unexpected error occured";
- $location.path('/Error')
- }
- return $q.reject(response);
- }
Code Example of an Interceptor
- <!DOCTYPE html>
- <html ng-app="interceptorApp">
-
- <head>
- <script src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
- <script>
- var testInterceptor = function ($q)
- {
- return {
- request: function (config)
- {
- console.log('request started...');
- },
- requestError: function (rejection)
- {
- console.log(rejection);
-
- return $q.reject(rejection);
- },
- response: function (result)
- {
- console.log('data for ' + result.data.name + ' received');
-
- result["testKey"] = 'testValue';
- console.log('request completed');
- return result;
- },
- responseError: function (response)
- {
- console.log('response error started...');
-
- return $q.reject(response);
- }
- }
- }
- interceptorApp = angular.module('interceptorApp', []).config(function ($httpProvider)
- {
- $httpProvider.interceptors.push(testInterceptor);
- });
- interceptorApp.controller('interceptorCtrl', ["$scope", "$http",
- function ($scope, $http)
- {
- $scope.getData = function ()
- {
- var data = $http.get('http://localhost:52332/testwebapi').
- success(function (data, status, headers, config)
- {
- $scope.Name = data.name;
- });
- };
- }
- ])
- </script>
- </head>
-
- <body ng-controller="interceptorCtrl"> {{ Name }}
- <input type="button" value="Click To Test Interceptors" ng-click="getData()" /> </body>
-
- </html>
Output
We see here that the console log has 'request started...’ and 'response error started...’ from the interceptors .
This was the basic understanding of HTTP Interceptors in AngularJS. Thanks for reading.