Can one use the Fetch API as a Request Interceptor?

泄露秘密 提交于 2020-01-30 04:59:18

问题


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.


回答1:


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)




回答2:


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);


来源:https://stackoverflow.com/questions/42578452/can-one-use-the-fetch-api-as-a-request-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!