http hook

class XMLHttp {
    request = function(param) {}
    ;
    response = function(param) {}
    ;
}
let httpCopy = new XMLHttp();

// 初始化 拦截XMLHttpRequest
function initXMLHttpRequest() {
    let open = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(...args) {
        let send = this.send;
        let _this = this
        let post_data = []
        this.send = function(...data) {
            post_data = data;
            return send.apply(_this, data)
        }
        // 请求前拦截
        httpCopy.request(args)

        this.addEventListener('readystatechange', function() {
            if (this.readyState === 4) {
                let config = {
                    url: args[1],
                    status: this.status,
                    method: args[0],
                    data: post_data
                }
                // 请求后拦截
                httpCopy.response({
                    config,
                    response: this.response
                })
            }
        }, false)
        return open.apply(this, args);
    }
}

// 初始化页面
(function() {
    // XMLHttpRequest 拦截
    httpCopy.request = function(param) {//   console.log(param, "---request");
    }
    ;
    httpCopy.response = function(res) {
        console.log(res, "---response");
    }
    // 初始化 XMLHttpRequest
    initXMLHttpRequest();

    // 模拟数据请求 (此处写自己要使用的请求)
    // request();

}
)();

  

posted @ 2022-11-13 16:36  一直闭眼看世界  阅读(39)  评论(0编辑  收藏  举报