【问题标题】:Can one use the Fetch API as a Request Interceptor?可以将 Fetch API 用作请求拦截器吗?
【发布时间】:2017-07-23 12:55:13
【问题描述】:

我尝试在每次使用 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);
    };
})();

很高兴知道是否有一种方法可以使用 Fetch API 完成同样的全局操作。

【问题讨论】:

    标签: javascript xmlhttprequest fetch-api


    【解决方案1】:

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

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

    Example on jsFiddle (因为 Stack Snippets 没有方便的 ajax 功能)

    【讨论】:

      【解决方案2】:

      就像您可以覆盖 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);
      

      【讨论】:

        猜你喜欢
        • 2021-08-07
        • 2018-01-07
        • 2019-09-12
        • 2023-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        相关资源
        最近更新 更多