Intercept HTTP requests – AJAX/jQuery

Intercept HTTP requests – AJAX/jQuery

Working in JavaScript we often need to make some HTTP requests to server. Requests could pass some information or try to get some of it. This is a typical functionality in client-server architecture. However, there are some cases that could be useful to do some action for each HTTP request. For example, we may want to add custom headers to all our requests or add authentication code to login into system. We can also capture every response from server to validate something or handle errors globally. This requirements could be met using interceptors. They give us an opportunity to handle HTTP request before sending and after answer receiving.

In this post I will show you how useful interceptors can be in few simple situations with few different technologies.

JavaScript (XMLHttpRequest)

Let’s imagine that we have an application written in vanilla JS. You have implemented authentication system based on token that is passed with every request. It is generated on server and send back in Authorization header to server to confirm user identification for each HTTP request. This functionality is similar to OAuth (http://oauth.net/articles/authentication/). Therefore you want to add this header to your HTTP mechanism globally. It can be easily modifying XMLHttpRequest prototype. Also you want to log each response status

(function(open) {
    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
        this.addEventListener("readystatechange", function() {
			if (this.readyState == 4) 
            { 
				console.log(this.status);
			}
        }, false);
        open.call(this, method, url, async, user, pass);
		this.setRequestHeader("Authorization", "Token 123")
    };
})(XMLHttpRequest.prototype.open);

In this example you can see two important things. In line 10 you can add your actions before request will be sent. While line 6 is the place where you can get response data and modify it.

Then you can execute some HTTP request and all magic will be done automatically.

var oReq = new XMLHttpRequest();
oReq.open("get", "www.example.com", true);
oReq.send();

JQuery

Now let’s imagine that you have the same problem as recently, but you should do this in jQuery. This will be much easier, because this library encapsulate each HTTP mechanism using special objects.

To intercept before sending a request you can use $.ajaxSetup function

$.ajaxSetup({
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', 'Token 123')
    }
});

But to capture responses you should use global callback functions (http://api.jquery.com/ajaxSuccess/, http://api.jquery.com/ajaxError/) as it’s showed below

$( document ).ajaxSuccess(function( event, request, settings ) {
	console.log(request.status);
});

$( document ).ajaxError(function( event, request, settings ) {
	console.log(request.status);
});