Javascript中的Http标头?

3 javascript firebug http http-headers

是否可以在JavaScript中收集HTTP标头?在使用Firebug几天后,这只是我的想法.在我发现的其中一篇文章中,在JavaScript中找不到HTTP头是不可能的,而在firebug中,我们可以看到响应头(客户端)

所以我的问题是我们可以在JavaScript中缓存HTTP标头吗?

Dan*_*llo 5

HTTP标头在JavaScript中不可用.

但是,您可以使用XMLHttpRequest同一域中的任何资源执行HEAD 请求:

var xhr = new XMLHttpRequest();

xhr.open('HEAD', '/', true);            // Relative path of resource

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    console.log(xhr.getAllResponseHeaders());
  }
}

xhr.send(null);
Run Code Online (Sandbox Code Playgroud)

以上将返回类似这样的内容(在此页面上的Firebug中运行):

Server: nginx 
Date: Fri, 09 Jul 2010 18:58:30 GMT 
Content-Type: text/html; charset=utf-8 
Connection: keep-alive 
Cache-Control: public, max-age=60 
Content-Length: 33273 
Content-Encoding: gzip 
Expires: Fri, 09 Jul 2010 18:59:31 GMT 
Last-Modified: Fri, 09 Jul 2010 18:58:31 GMT 
Vary: * 
Run Code Online (Sandbox Code Playgroud)

您可以轻松获得单个标头的值,如下所示:

xhr.getResponseHeader('Last-Modified');
Run Code Online (Sandbox Code Playgroud)