如何在发送之前拦截AJAX调用并更改目标主机

时间:2019-01-10 18:28:41

标签: javascript ajax http xmlhttprequest

要拦截本地ajax调用,我发现以下代码片段正常工作

(function(XHR) {
    "use strict";

    var open = XHR.prototype.open;
    var send = XHR.prototype.send;

    XHR.prototype.open = function(method, url, async, user, pass) {
        this._url = url;
        open.call(this, method, url, async, user, pass);
    };

    XHR.prototype.send = function(data) {
        var self = this;
        var oldOnReadyStateChange;
        var url = this._url;
        console.log(url);

        function onReadyStateChange() {
            if(self.readyState == 4 /* complete */) {
                /* This is where you can put code that you want to execute post-complete*/
                /* URL is kept in this._url */
            }

            if(oldOnReadyStateChange) {
                oldOnReadyStateChange();
            }
        }

        /* Set xhr.noIntercept to true to disable the interceptor for a particular call */
        if(!this.noIntercept) {            
            if(this.addEventListener) {
                this.addEventListener("readystatechange", onReadyStateChange, false);
            } else {
                oldOnReadyStateChange = this.onreadystatechange; 
                this.onreadystatechange = onReadyStateChange;
            }
        }

        send.call(this, data);
    }
})(XMLHttpRequest);

但是我要做的是更改目标主机,所以我不想将这些ajax请求运行在当前网站上,而是希望将它们定向到另一个网站。

我尝试了this.setRequestHeader('Host', 'example.com');,但是在控制台中收到一条错误消息,告诉我我正在尝试设置禁止的标题。

实际上我可以提出另一个ajax请求,但是切换主机将对我来说更加方便。

谢谢

0 个答案:

没有答案