How to get headers of the response from fetch

16,034

You can't access all the headers when requesting cross-domain content via ajax. You can access all headers if origin is same.

As explained in W3 Specifications here, only Content-Type, Last-modified, Content-Language, Cache-Control, Expires, Pragma headers are accessible.

Further https://httpbin.org/get send only Content-Type header from list of accessible headers so, you got that only.

Edit: You can expose non-standard CORS response headers by sending Access-Control-Expose-Headers with the headers you want the client to access on the response.

Share:
16,034

Related videos on Youtube

udnisap
Author by

udnisap

I love to explore new ideas

Updated on June 06, 2022

Comments

  • udnisap
    udnisap almost 2 years

    I am using fetch on chrome Version 52.0.2743.82 (64-bit). I want to get all the headers in the response. Following snippet only return content-type but if you peek into chrome dev tools it shows many other response headers. How to get other headers from fetch.

      fetch('https://httpbin.org/get')
        .then(response => {
           const headers = response.headers.entries();
           let header = headers.next();
           while (!header.done){
             console.log(headers.value);
             header = header.next();
           }
        })
    

    I tried polyfilling(manually overriding) the github implementation. Still no luck.

    • KumarM
      KumarM almost 8 years
      If you know what header you are looking for you could try response.headers.get('header-name')
    • KumarM
      KumarM almost 8 years
      Looking at the compatibility table at the bottom of this page it doesn't say that chrome supports entries() yet. developer.mozilla.org/en-US/docs/Web/API/Headers
  • jasonseminara
    jasonseminara over 7 years
    This was super helpful. For those Rails 5 developers, editing config/initializers/cors.rb worked. I added: expose: ['Location'], to the resource '*' statement
  • Gil Beyruth
    Gil Beyruth almost 6 years
    Add your custom header for the Access-Control-Expose-Headers on the server, to allow the browser to get custom headers on CORS. res.setHeader('Access-Control-Expose-Headers', 'my-custom-header');