可以将Fetch API用作请求拦截器吗? [英] Can one use the Fetch API as a Request Interceptor?

查看:419
本文介绍了可以将Fetch API用作请求拦截器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用Fetch API向服务器发出的每个请求之后,我都试图运行一些简单的JS函数.我一直在寻找该问题的答案,但未找到任何答案,可能是由于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.

我一直在用XMLHttpRequest这样做,就像这样:

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

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

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

推荐答案

由于fetch返回承诺,因此您可以通过覆盖fetch将自己插入承诺链:

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

关于jsFiddle的示例 (因为堆栈代码段没有方便的ajax功能)

这篇关于可以将Fetch API用作请求拦截器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆