1

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.

2
  • which browser are you using? Commented Apr 3, 2020 at 0:47
  • @klanmiko Google Chrome 83 Commented Apr 3, 2020 at 18:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So basically there is no way around it without using a proxy. That's anti-climactic, but clear.
Correct. Or otherwise you could ask for access to set-cookie headers for example and therefore get access to cookies your domain shouldn’t see. Just one example of the dangers of unrestricted access.
And thanks for the correction. You are correct - been a while since I looked at this!!
0

I can't reproduce this. MDN says that all headers will be returned in lowercase.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.