是否可以在每次向服务器发出请求之前调用 Javascript 函数?

iro*_*roh 1 javascript http

我在本地存储中有一些内容。每次通过调用类似 (xhr.setRequestHeader('custom-header', 'value');) 向服务器发出请求时,我想在 http 标头中发送此信息。我希望自动调用它,而不是在每个请求之前调用执行此任务的函数。

aps*_*ers 6

这可以通过覆盖该方法轻松完成send

// save the real `send`
var realSend = XMLHttpRequest.prototype.send;

// replace `send` with a wrapper
XMLHttpRequest.prototype.send = function() {
    this.setRequestHeader("X-Foobar", "my header content");

    // run the real `send`
    realSend.apply(this, arguments);
}
Run Code Online (Sandbox Code Playgroud)

这变成XMLHttpRequest.prototype.send了一个函数,可以执行一些任意操作(这里是在实例X-Foobar上设置请求标头XMLHttpRequest),然后使用真正的send方法执行实际的 Ajax 请求。