代码之家  ›  专栏  ›  技术社区  ›  keparo bshirley

在JavaScript中访问网页的HTTP头

  •  356
  • keparo bshirley  · 技术社区  · 16 年前

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

    有关 this question

    相关的:
    How do I access the HTTP request header fields via JavaScript?

    16 回复  |  直到 8 年前
        1
  •  396
  •   Randy    7 年前

    无法读取当前标题。您可以对同一URL发出另一个请求并读取其标题,但不能保证标题与当前URL完全相同。


    使用以下JavaScript代码通过执行 get

    var req = new XMLHttpRequest();
    req.open('GET', document.location, false);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    alert(headers);
    
        2
  •  322
  •   Community CDub    4 年前

    repeatedly asked ,因为有些人希望在不发出另一个响应头的情况下获取原始页面请求的实际响应头。


    对于AJAX请求:

    getAllResponseHeaders() 方法它是XMLHttpRequestAPI的一部分。要了解如何应用此功能,请查看 fetchSimilarHeaders() 功能如下。请注意,这是解决某些应用程序不可靠的问题的方法。

    myXMLHttpRequest.getAllResponseHeaders();
    

    这不会为您提供有关原始页面请求的HTTP响应头的信息,但可以使用它对这些头是什么进行有根据的猜测。关于这一点的更多信息将在下面介绍。


    这个问题在几年前首次提出,专门询问如何获取 (即运行javascript的同一页面)。这与简单地获取任何HTTP请求的响应头是完全不同的问题。对于初始页面请求,javascript不容易获得标题。如果通过AJAX再次请求相同的页面,则所需的标题值是否可靠且充分一致将取决于您的特定应用程序。

    下面是一些解决这个问题的建议。


    如果响应基本上是静态的,并且请求之间的头不会有太大变化,那么您可以对当前所在的同一页面发出AJAX请求,并假设它们是相同的值,这些值是页面HTTP响应的一部分。这允许您使用上面描述的漂亮的XMLHttpRequestAPI访问所需的头。

    function fetchSimilarHeaders (callback) {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (request.readyState === XMLHttpRequest.DONE) {
                //
                // The following headers may often be similar
                // to those of the original page request...
                //
                if (callback && typeof callback === 'function') {
                    callback(request.getAllResponseHeaders());
                }
            }
        };
    
        //
        // Re-request the same page (document.location)
        // We hope to get the same or similar response headers to those which 
        // came with the current page, but we have no guarantee.
        // Since we are only after the headers, a HEAD request may be sufficient.
        //
        request.open('HEAD', document.location, true);
        request.send(null);
    }
    

    如果您确实必须依赖于请求之间的值是一致的,那么这种方法将是有问题的,因为您不能完全保证它们是相同的。这将取决于您的特定应用程序,以及您是否知道您所需要的值是不会从一个请求更改到下一个请求的。


    (浏览器对象模型),浏览器通过查看标题来确定。其中一些属性直接反映HTTP头(例如。 navigator.userAgent 设置为HTTP的值 User-Agent 标题字段)。通过嗅探可用的属性,您可能能够找到您需要的内容,或者找到一些指示HTTP响应所包含内容的线索。


    如果您控制服务器端,则可以在构造完整响应时访问任何您喜欢的头。值可以与页面一起传递给客户机,存储在一些标记中,或者可能存储在内联JSON结构中。如果希望javascript可以使用每个HTTP请求头,可以在服务器上迭代它们,并将它们作为标记中的隐藏值发送回。以这种方式发送头值可能不太理想,但您当然可以针对所需的特定值进行发送。这个解决方案也可以说是低效的,但如果您需要它,它可以完成这项工作。

        3
  •  31
  •   Marius Bancila    10 年前

    使用 XmlHttpRequest

    最好的办法就是做一个简单的测试 HEAD 请求,然后检查标题。

    有关执行此操作的一些示例,请参见 http://www.jibbering.com/2002/4/httprequest.html

        4
  •  30
  •   Gaël Métais    6 年前

    服务人员的解决方案

    服务人员能够访问网络信息,包括标题。好的方面是它可以处理任何类型的请求,而不仅仅是XMLHttpRequest。

    工作原理:

    1. 在您的网站上添加服务人员。
    2. 让服务人员 fetch respondWith 作用
    3. 当响应到达时,阅读标题。
    4. postMessage 作用

    工作示例:

    https://github.com/gmetais/sw-get-headers .

    限制:

        5
  •  18
  •   savetheclocktower    16 年前

    Set-Cookie 响应头和cookie可以在JavaScript中读取。不过,正如凯帕罗所说,最好只对一两个标题执行此操作,而不是对所有标题执行此操作。

        6
  •  14
  •   Diego    7 年前

    对于那些正在寻找将所有HTTP头解析为可以作为字典访问的对象的人 headers["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"]
    
        7
  •  7
  •   jakub.g    3 年前

    没有 附加HTTP调用

    虽然这是不可能的 一般来说

    你可以用 Server-Timing 头来公开任意键值数据,JavaScript可以读取该数据。

    no Safari yet 截至2021.09年,没有立即的运输计划;没有(IE)

    server-timing: key;desc="value"
    
    server-timing: key1;desc="value1"
    server-timing: key2;desc="value2"
    
    • 或者使用它的压缩版本,在一个标题中公开多个数据段,以逗号分隔。
    server-timing: key1;desc="value1", key2;desc="value2"
    

    举例说明如何 Wikipedia 使用此标头公开有关缓存命中/未命中的信息:

    Usage of server-timing response header on Wikipedia

    代码示例(需要说明Safari和IE中缺少浏览器支持):

    if (window.performance && performance.getEntriesByType) { // avoid error in Safari 10, IE9- and other old browsers
        let navTiming = performance.getEntriesByType('navigation')
        if (navTiming.length > 0) { // still not supported as of Safari 14...
            let serverTiming = navTiming[0].serverTiming
            if (serverTiming && serverTiming.length > 0) {
                for (let i=0; i<serverTiming.length; i++) {
                    console.log(`${serverTiming[i].name} = ${serverTiming[i].description}`)
                }
            }
        }
    }
    

    这个日志 cache = hit-front 在支持的浏览器中。

    笔记:

        8
  •  6
  •   David Winiecki    12 年前

    您无法访问http头,但其中提供的一些信息在DOM中可用。例如,如果您想查看http引用器(sic),请使用document.referer。对于其他http头,可能还有其他类似的情况。试着用谷歌搜索你想要的特定内容,比如“http referer javascript”。

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

        9
  •  5
  •   user4020527 Leo    7 年前

    要求 头,您可以在执行XmlHttpRequests时创建自己的头。

    var request = new XMLHttpRequest();
    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    request.open("GET", path, true);
    request.send(null);
    
        10
  •  4
  •   Fulup    10 年前

    像许多人一样,我一直在挖网,却没有真正的答案:(

    尽管如此,我还是找到了一条可以帮助他人的旁路。在我的情况下,我完全控制我的web服务器。事实上,它是我的应用程序的一部分(请参阅end reference)。我很容易将脚本添加到http响应中。我修改了我的httpd服务器,在每个html页面中插入一个小脚本。我只在我的头构建之后推一个额外的“js脚本”行,它在我的浏览器[I choose location]中从我的文档中设置一个现有变量,但任何其他选项都是可能的。虽然我的服务器是用nodejs编写的,但毫无疑问,同样的技术也可以从PHP或其他应用程序中使用。

      case ".html":
        response.setHeader("Content-Type", "text/html");
        response.write ("<script>location['GPSD_HTTP_AJAX']=true</script>")
        // process the real contend of my page
    

    现在,从我的服务器加载的每个html页面都会在接收时由浏览器执行此脚本。然后,我可以轻松地从JavaScript检查变量是否存在。在我的用例中,我需要知道是否应该使用JSON或JSON-P配置文件来避免CORS问题,但同样的技术也可以用于其他目的[即:在开发/生产服务器之间进行选择,从服务器获取REST/API密钥,等等]

    在浏览器上,您只需要直接从JavaScript检查变量,如我的示例中所示,我使用它来选择Json/JQuery配置文件

     // Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP
      var corsbypass = true;  
      if (location['GPSD_HTTP_AJAX']) corsbypass = false;
    
      if (corsbypass) { // Json & html served from two different web servers
        var gpsdApi = "http://localhost:4080/geojson.rest?jsoncallback=?";
      } else { // Json & html served from same web server [no ?jsoncallback=]
        var gpsdApi = "geojson.rest?";
      }
      var gpsdRqt = 
          {key   :123456789 // user authentication key
          ,cmd   :'list'    // rest command
          ,group :'all'     // group to retreive
          ,round : true     // ask server to round numbers
       };
       $.getJSON(gpsdApi,gpsdRqt, DevListCB);
    

    https://www.npmjs.org/package/gpsdtracking

        11
  •  4
  •   j.j.    5 年前

    艾伦·拉隆德的联系让我很开心。 只是在这里添加一些简单的html代码。
    可与任何合理的浏览器配合使用,包括IE9+和Presto-Opera12。

    <!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()
    https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
    caniuse.com
    工作示例代码:
    <!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>
    
        12
  •  4
  •   shaedrich Gabin traverse    3 年前

    将标题作为更方便的对象获取(改进 Raja's answer ):

    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;
    }, {});
    
        13
  •  3
  •   mkj java seeker    8 年前

    我刚刚进行了测试,这对我使用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
    
        14
  •  3
  •   Jorgesys    7 年前

    这是获取所有响应标题的脚本:

    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);
    

    因此具有响应头。

    enter image description here

    enter image description here

        15
  •  3
  •   shaedrich Gabin traverse    3 年前

    使用mootools,您可以使用 this.xhr.getAllResponseHeaders()

        16
  •  -1
  •   Wilt    8 年前

    这是一个老问题。不确定何时支持变得更广泛,但 getAllResponseHeaders() getResponseHeader() 现在看起来相当标准: http://www.w3schools.com/xml/dom_http.asp

        17
  •  -1
  •   Ollie Williams    7 年前

    例如,在Express中,以下工作:

    app.get('/somepage', (req, res) => { res.render('somepage.hbs', {headers: req.headers}); }) 然后,这些头在模板中可用,因此可以直观地隐藏,但包含在标记中,并由客户端javascript读取。

        18
  •  -2
  •   Santhosh N    6 年前

    如果您想从JQuery/JavaScript获取请求头,答案是否定的。其他解决方案是创建一个aspx页面或jsp页面,那么我们可以轻松访问请求头。