Search code examples
javascriptajaxxmlhttprequesthttp-headersresponse-headers

How do I fetch all headers in Javascript?


Quick and dirty experiment:

function fetchHead(url) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            console.log(request.getAllResponseHeaders())
        }
    }

    request.open('HEAD', url, true)
    request.send(null)
}

It only shows three headers: ["cache-control", "content-type", "expires"]. But there are a dozen headers in the actual response, as seen in the Network Inspector in the Development Toolbar.

Is there any (other) way to get all headers in Javascript? Is it possible (at all) to read a custom response header from within Javascript?

PS - The response does have Access-Control-Allow-Origin: *. Somehow the browsers does seem to strip out a lot of the headers though.


Solution

  • For security reasons browsers restrict access to most HTTP Headers calls via XMLHttpRequest. Best reference for this is probably the Fetch standard.

    These restricted list can be expanded by the server returning a Access-Control-Expose-Headers header telling the browser which headers are safe for JavaScript to have access to.