如何通过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

其他回答

为了获得头部作为一个更方便的对象(改进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报头,但是其中提供的一些信息在DOM中是可用的。例如,如果你想查看http引用器(原文如此),使用document.referrer。可能还有其他类似的http头文件。试着谷歌一下你想要的具体内容,比如“http referer javascript”。

我知道这应该是显而易见的,但我一直在搜索像“http headers javascript”这样的东西,而我真正想要的只是引用器,并没有得到任何有用的结果。我不知道我怎么没意识到我可以问个更具体的问题。

向JavaScript发送报头信息的另一种方法是通过cookie。服务器可以从请求头中提取它需要的任何数据,并将它们发送回Set-Cookie响应头中——并且cookie可以在JavaScript中读取。但是,正如keparo所说,最好只对一个或两个头文件执行此操作,而不是对所有头文件执行此操作。

如前所述,如果您控制服务器端,那么应该可以在初始响应中将初始请求头发送回客户端。

以Express为例,以下工作:

App.get ('/somepage', (req, res) => { res.render(“somepage。Hbs ', {headers: req.headers}); }) 然后在模板中可以使用头文件,因此可以在视觉上隐藏,但包含在标记中并由客户端javascript读取。

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>