返回

xhr封装、xhr请求重发、Promise封装xhr、fetch请求重发

前端

1. xhr封装

(1)封装一个简单的xhr对象

function createXHR() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

(2)封装一个带参数的xhr对象

function createXHRWithParams(method, url, params) {
    let xhr = createXHR();
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
    return xhr;
}

2. xhr请求重发

(1)封装一个xhr请求重发函数

function retryXHR(xhr, url, params, retryCount) {
    if (retryCount <= 0) {
        return;
    }
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 请求成功
            } else {
                // 请求失败,重试
                retryXHR(xhr, url, params, retryCount - 1);
            }
        }
    };
}

3. Promise封装xhr

(1)封装一个Promise封装xhr的函数

function promisifyXHR(xhr) {
    return new Promise((resolve, reject) => {
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response);
            } else {
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => {
            reject(xhr.statusText);
        };
    });
}

4. fetch请求重发

(1)封装一个fetch请求重发函数

function retryFetch(url, params, retryCount) {
    if (retryCount <= 0) {
        return;
    }
    fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: params,
    }).then((res) => {
        if (res.ok) {
            return res.json();
        } else {
            // 请求失败,重试
            retryFetch(url, params, retryCount - 1);
        }
    }).then((data) => {
        // 请求成功
    }).catch((error) => {
        // 请求失败,重试
        retryFetch(url, params, retryCount - 1);
    });
}

以上就是使用xhr和fetch实现请求封装、请求重发的方法。