如何监视和拦截所有动态 AJAX 请求并重新发送它们?

问题描述

如何监控和拦截所有动态 AJAX 请求并重新发送? 我该怎么做?

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(value) {

    this.addEventListener("error",function(){
        /* 
           Need Resend It By XMLHttpRequest In Here
           All Resend Request Are Dynamic Generate
           Such As "new XMLHttpRequest(this).send()"
           Use AJAX Are Also OK
        */
    },false);
    this.realSend(value);
};

解决方法

尝试以下操作。显然,它适用于在执行此代码段后进行的 AJAX 调用,因此您需要尽快执行它。

我不确切知道您的用例是什么,但请注意,如果错误原因未解决,失败的请求可能会失败 100 万次。使用此代码,每次重试都等于前一次失败。

另请注意,一旦成功,您将需要进行一些修改才能访问嵌套请求的响应。

// PROXY 'open' INSTEAD OF 'send' SO YOU CAN CAPTURE REQUESTS EARLY.
XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;

// WE NEED TO TRACK RETRY NUMBER PER REQUEST TO AVOID INFINITE LOOPS.
XMLHttpRequest.prototype._maxRetry = 5;
XMLHttpRequest.prototype._currentRetry = 0;

XMLHttpRequest.prototype.open = function open(...args) {

    if (!this._currentRetry) {
        console.log('REQUEST CAPTURED.');
    }

    this.addEventListener('error',() => {
        // ABORT PREVIOUS REQUEST.
        this.abort();

        // CHECK NUMBER OF RETRIES.
        if (this._currentRetry >= this._maxRetry) {
          console.log('MAX RETRY REACHED.');
          return;
        }

        console.log(`RETRYING ${this._currentRetry} of ${this._maxRetry}.`);

        // CREATE NEW REQUEST INSTANCE.
        const req = new XMLHttpRequest();
        
        // COPY UPDATED RETRY NUMBERS TO NEW INSTANCE.
        req._maxRetry = this._maxRetry;
        req._currentRetry = this._currentRetry + 1;
        req.responseType = this.responseType;
        
        // SEND NEW REQUEST USING PREVIOUS REQUEST ARGUMENTS.
        req.open(...args);
        req.send();
    });

    // CALL ORIGINAL 'open' METHOD.
    this._open(...args);
};

const test = new XMLHttpRequest();

test.open('GET','https://asfashdg');
test.send();