最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can one use the Fetch API as a Request Interceptor? - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Mar 3, 2017 at 12:11 T.J. Crowder 1.1m199 gold badges2k silver badges1.9k bronze badges asked Mar 3, 2017 at 12:05 Roger B. H.Roger B. H. 1991 gold badge2 silver badges8 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 14

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)

Just like you could overwrite the open method you can also overwrite the global fetch method with an intercepting one:

fetch = (function (origFetch) {
    return function myFetch(req) {
        var result = origFetch.apply(this, arguments);
        result.then(someFunctionToDoSomething);
        return result; // or return the result of the `then` call
    };
})(fetch);
发布评论

评论列表(0)

  1. 暂无评论