Niroj Dahal

Intercept Request and Response in Fetch API

Published 2 years ago 5 min read
image

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

Fetch provides a generic definition of Request and Response objects (and other things involved with network requests). This will allow them to be used wherever they are needed in the future, whether it's for service workers, Cache API, and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions).

For more detail, visit MSDN Docs MDN | Web APIs

For making a request and fetching a resource,we use the fetch() method.

Unlike JQuery ajax which has ajaxComplete method that allows us to invoke a function after completion of a request (which may be either error or succes), fetch doesnot provide the method that we can use to intercept the request and response.So, I came up with the function that intercepts request and response

function interceptedFetchRequest(...fetchParams) {			
return new Promise(async function (resolveThis, rejectThis) {
// intercept request and do as you need
 var data = fetch(...fetchParams);
 var response = await data;
				
// intercept response
// example is below
if (response.url.toLowerCase().includes("Account/Login".toLowerCase())) {
     rejectThis(new SessionTimeoutError("Session Timeout Occured"));
      showLoginPageInPopup();
   }
   else {
            resolveThis(response);
        }
    });
}    

Now, instead of calling fetch() method to make request, use the interceptedFetchRequest()

try
{
  const response = await interceptedFetchRequest(url, options);
	// you can use response in same way as you would use with fetch
  let jsonData = await response.json(); 
  } catch (e) {              
}

Thanks for reading!!