Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one use the Fetch API as a Request Interceptor?

I'm trying to run some simple JS functions after every request to the server with the Fetch API. I've searched for an answer to this question, but haven't found any, perhaps due to the fact that the Fetch API is relative recent.

I've been doing this with XMLHttpRequest like so:

(function () {
   var origOpen = XMLHttpRequest.prototype.open;
   XMLHttpRequest.prototype.open = function () {
      this.addEventListener('load', function () {

         someFunctionToDoSomething();   

       });
       origOpen.apply(this, arguments);
    };
})();

Would be great to know if there's a way to accomplish this very same global thing using the Fetch API.

like image 982
Roger B. H. Avatar asked Mar 03 '17 12:03

Roger B. H.


People also ask

What can you do with fetch API?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do I intercept API request?

To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request. In the listeners, you can: Get access to request headers and bodies and response headers.

Is the fetch API a GET request?

It allows you to make an HTTP request, i.e., either a GET request (for getting data) or POST request (for posting data). The basic fetch request can be explained by the following code: 1 2 3 4 5 6 7 8 9 10 11 12 fetch('url') . then(response => { //handle response console.

What are disadvantages of fetch API?

more complicated API, request and response concepts are mixed together. lacks streaming, whole response is going to buffer in memory, not available for binary data.


1 Answers

Since fetch returns a promise, you can insert yourself in the promise chain by overriding fetch:

(function () {
    var originalFetch = fetch;
    fetch = function() {
        return originalFetch.apply(this, arguments).then(function(data) {
            someFunctionToDoSomething();
            return data;
        });
    };
})();

Example on jsFiddle (since Stack Snippets don't have the handy ajax feature)

like image 163
T.J. Crowder Avatar answered Nov 15 '22 20:11

T.J. Crowder