如何通过JavaScript访问页面的HTTP响应头?

与此问题相关,该问题已被修改为询问访问两个特定的HTTP报头。

相关: 如何通过JavaScript访问HTTP请求报头字段?


当前回答

我刚刚测试过,这适用于我使用Chrome版本28.0.1500.95。

我需要下载一个文件并读取文件名。文件名在头文件中,所以我做了以下工作:

var xhr = new XMLHttpRequest(); 
xhr.open('POST', url, true); 
xhr.responseType = "blob";
xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4) {
        success(xhr.response); // the function to proccess the response

        console.log("++++++ reading headers ++++++++");
        var headers = xhr.getAllResponseHeaders();
        console.log(headers);
        console.log("++++++ reading headers end ++++++++");

    }
};

输出:

Date: Fri, 16 Aug 2013 16:21:33 GMT
Content-Disposition: attachment;filename=testFileName.doc
Content-Length: 20
Server: Apache-Coyote/1.1
Content-Type: application/octet-stream

其他回答

使用XmlHttpRequest可以调出当前页面,然后检查响应的http报头。

最好的情况是只做一个HEAD请求,然后检查头。

要了解一些这样做的例子,请查看http://www.jibbering.com/2002/4/httprequest.html

这只是我的个人意见。

为了获得头部作为一个更方便的对象(改进Raja的答案):

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
    if (b.length) {
        var [ key, value ] = b.split(': ');
        a[key] = value;
    }
    return a;
}, {});

对于那些寻找一种方法来解析所有HTTP头到一个对象,可以访问作为字典头["content-type"],我已经创建了一个函数parseHttpHeaders:

function parseHttpHeaders(httpHeaders) {
    return httpHeaders.split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do:  headers["content-type"]

这是我的脚本,以获得所有的响应头:

var url = "< URL >";

var req = new XMLHttpRequest();
req.open('HEAD', url, false);
req.send(null);
var headers = req.getAllResponseHeaders();

//Show alert with response headers.
alert(headers);

结果有响应头。

这是一个使用Hurl.it的对比测试:

Allain Lalonde的链接让我很开心。 只是在这里添加了一些简单的html代码。 适用于任何合理的浏览器,年龄加上IE9+和preto - opera 12。

<!DOCTYPE html>
<title>(XHR) Show all response headers</title>

<h1>All Response Headers with XHR</h1>
<script>
 var X= new XMLHttpRequest();
 X.open("HEAD", location);
 X.send();
 X.onload= function() { 
   document.body.appendChild(document.createElement("pre")).textContent= X.getAllResponseHeaders();
 }
</script>

注意:你得到第二个请求的头,结果可能不同于最初的请求。

另一种方法是更现代的fetch() API https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch 根据caniuse.com, Firefox 40, Chrome 42, Edge 14, Safari 11都支持它 工作示例代码:

<!DOCTYPE html>
<title>fetch() all Response Headers</title>

<h1>All Response Headers with fetch()</h1>
<script>
 var x= "";
 if(window.fetch)
    fetch(location, {method:'HEAD'})
    .then(function(r) {
       r.headers.forEach(
          function(Value, Header) { x= x + Header + "\n" + Value + "\n\n"; }
       );
    })
    .then(function() {
       document.body.appendChild(document.createElement("pre")).textContent= x;
    });
 else
   document.write("This does not work in your browser - no support for fetch API");
</script>