Accessing the web page's HTTP Headers in JavaScript

前端 未结 17 2613
日久生厌
日久生厌 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:35

    For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"], I've created a function 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"]
    

提交回复
热议问题