4

I have a react application using ES6 fetch API to call a rest endpoint using CORS. The fetch call work just fine, but I'm unable to get the response headers that are being sent from the server. I can see the response headers in Chromes devtools so I know they are being sent back to me; however access to them in code doesn't seem to work for me. Here is the code (its basic fetch promise-chaining):

fetch(url)
  .then(response => {
    for (let header of response.headers) { < -- - headers is empty
      console.log(header);
    }
    return response;
  });

But response.headers is empty. But I can clearly see the headers in Chrome. Is there a reason why the fetch call is blocking me from viewing them? What do I need to get access to these headers? The server stores some application specific headers that we would love to use.

UPDATE: I was able to fix this by having the server add this to the response of the OPTION request:

response.setHeader("Access-Control-Expose-Headers", "X-Custom-Header");

Now on the response of the fetch command, I can do the following:

const customHeader = response.headers.get('X-Custom-Header');

Thank you Karim for the help on this!

Gerb
  • 883
  • 12
  • 31

1 Answers1

5

To get a specific header you need to call response.headers.get(key)

and the iterable object is response.headers.entries and not response.headers

for (let header of response.headers.entries()) {
  console.log(header);
}

https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries

In addition, in a cors scenario only some headers are exposed to the app, thus not all the headers you see on the chrome dev tools are necessarily available at application level. For further details check this answer:

Reading response headers with Fetch API

Karim
  • 8,454
  • 3
  • 25
  • 33
  • I tried that with no avail. response.headers.entries() returns an empty iterator. And response.headers.get('my-custom-header') returns undefined even when I'm looking at it in the Chrome DevTools. Very strange. – Gerb Apr 18 '19 at 15:26
  • 2
    keep in mind that only some headers are exposed in a cors scenario: https://stackoverflow.com/questions/43344819/reading-response-headers-with-fetch-api?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Karim Apr 18 '19 at 15:40
  • 3
    Karim, thank you. I was able to figure this out, by having the server add this to the response header of the OPTIONS request: response.setHeader("Access-Control-Expose-Headers", "X-Auth-Access"); – Gerb Apr 18 '19 at 15:56