javascript - 如何在 xhr 对象上设置 getAllResponseHeaders()

标签 javascript http-headers xmlhttprequest

我正在使用以下代码记录 xhr 请求:

(function(open) {
  XMLHttpRequest.prototype.open = function(method, url, async) {

if (..something..) 
{

...
open.call(this, method, url, async);
...

}

  };

})(XMLHttpRequest.prototype.open);

所以现在我想获取响应 header ,例如 console.log(getAllResponseHeaders()) 我尝试在代码中的任何地方实现它,但我没有得到任何结果,这意味着没有记录任何内容。在哪里或如何获取响应 header ?

最佳答案

请记住, header 仅在到达后才存在,而不是之前。这意味着您必须使用事件监听器来捕获它们。根据状态4,它们肯定存在。

(function(open, headers) {
    var headhandle = function () {
        if (this.readyState === 4) console.log(headers.call(this));
    };
    XMLHttpRequest.prototype.open = function(method, url, async) {
        this.addEventListener('readystatechange', headhandle);
        open.call(this, method, url, async);
    };
}(XMLHttpRequest.prototype.open, XMLHttpRequest.prototype.getAllResponseHeaders));

var x = new XMLHttpRequest();
x.open();
x.send();
/*
Date: Tue, 31 Dec 2013 13:43:42 GMT
Content-Encoding: gzip
Vary: *
Last-Modified: Tue, 31 Dec 2013 13:43:43 GMT
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Cache-Control: public, max-age=60
Content-Length: 14317
Expires: Tue, 31 Dec 2013 13:44:43 GMT
*/

使用 readyState === 3 进行测试,但没有给出结果,因此您肯定需要等待 4

关于javascript - 如何在 xhr 对象上设置 getAllResponseHeaders(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20858206/

相关文章:

javascript - 我想在点击 100 次后停止此功能

javascript - AngularJS:在任何部分页面 Controller 之前调用特定函数

flask - AWS 弹性 Beanstalk : HTTP Header not appearing in Flask application

javascript - 访问node.js中xhr请求发送的数据

Javascript XML 解析器

Web Worker 中的 Ajax 限制

javascript - 如何定义文本框值 null = 0 且 value = 1?使用 JavaScript

javascript - 在内容可编辑的 div 中获取插入符位置

c# - HttpWebRequest 到由 IP 地址指定的服务器上的 SSL 网站 (WebProxy)

c# - HttpWebRequest.Headers.Add ("Cookie",值)与 HttpWebRequest.CookieContainer