可以使用Fetch API作为请求拦截器吗?

Rog*_* H. 5 javascript xmlhttprequest fetch-api

我试图在使用Fetch API向服务器发出每个请求后运行一些简单的JS函数.我已经搜索了这个问题的答案,但是没有找到任何答案,可能是因为Fetch API是相对较新的.

我一直这样做XMLHttpRequest:

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

         someFunctionToDoSomething();   

       });
       origOpen.apply(this, arguments);
    };
})();
Run Code Online (Sandbox Code Playgroud)

很高兴知道是否有办法使用Fetch API完成同样的全局事务.

T.J*_*der 10

由于fetch返回了一个promise,您可以通过覆盖将自己插入到promise链中fetch:

(function () {
    var originalFetch = fetch;
    fetch = function() {
        return originalFetch.apply(this, arguments).then(function(data) {
            someFunctionToDoSomething();
            return data;
        });
    };
})();
Run Code Online (Sandbox Code Playgroud)

关于jsFiddle的示例 (因为Stack Snippets没有方便的ajax功能)

  • 这三个字符的缩进吓坏了我:-) (2认同)

Ber*_*rgi 5

就像您可以覆盖该open方法一样,您也可以fetch使用一个拦截方法来覆盖全局方法:

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);
Run Code Online (Sandbox Code Playgroud)