简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM