Accessing the web page's HTTP Headers in JavaScript

前端 未结 17 2653
日久生厌
日久生厌 2020-11-21 04:53

How do I access a page\'s HTTP response headers via JavaScript?

Related to this question, which was modified to ask about accessing two specific HTTP headers.

<
相关标签:
17条回答
  • 2020-11-21 05:46

    As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response.

    In Express, for example, the following works:

    app.get('/somepage', (req, res) => { res.render('somepage.hbs', {headers: req.headers}); }) The headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.

    0 讨论(0)
  • 2020-11-21 05:47

    To get the headers as an object which is handier (improvement of 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;
    }, {});
    console.log(headers);
    
    0 讨论(0)
  • 2020-11-21 05:48

    You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like "http referer javascript".

    I know this should be obvious, but I kept searching for stuff like "http headers javascript" when all I really wanted was the referer, and didn't get any useful results. I don't know how I didn't realize I could make a more specific query.

    0 讨论(0)
  • 2020-11-21 05:50

    It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.


    Use the following JavaScript code to get all the HTTP headers by performing a get request:

    var req = new XMLHttpRequest();
    req.open('GET', document.location, false);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    alert(headers);
    
    0 讨论(0)
  • 2020-11-21 05:50

    If we're talking about Request headers, you can create your own headers when doing XmlHttpRequests.

    var request = new XMLHttpRequest();
    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    request.open("GET", path, true);
    request.send(null);
    
    0 讨论(0)
提交回复
热议问题