1

I am trying to programmatically access the headers of a response.

PS: Using Chrome. If I add a breakpoint and inspect the response object, it looks like it has no headers.

If I try print of the headers, both of these log statements show {}:

    const response = await fetch(request);
    console.log('headers stringify:', response.headers);
    console.log('headers:', JSON.stringify(response.headers));

However in the Chrome dev tools Network tab it shows the response had headers. How does one access the headers of a response object?

run_the_race
  • 1,344
  • 2
  • 36
  • 62
  • 1
    What headers are you seeing in the Network tab? And what do you see when you use [`get`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/get) to access one of them? (E.g., if one of the headers is `Example`, what do you get for `console.log(response.headers.get("Example"));`?) – T.J. Crowder Jan 23 '22 at 10:15
  • 2
    I think this question may help you: https://stackoverflow.com/questions/48413050/missing-headers-in-fetch-response In short: you don't see any headers because you are not printing them properply. – aLittleSalty Jan 23 '22 at 10:19

1 Answers1

1

Thanks to @alittleSalty for the link which explains the headers are an iterable, and can be seen with:

response.headers.forEach((value, key) => console.log("header:", key, 'value:', value));
run_the_race
  • 1,344
  • 2
  • 36
  • 62
  • If the answer aLittleSalty linked answers this question (which makes sense), don't post that as an answer, close the question as a duplicate instead. – T.J. Crowder Jan 23 '22 at 10:29
  • Fair enough, although this answer does have value in that it shows how to get the key/value pairs, which to me are provided in reverse order to whats expected. – run_the_race Jan 23 '22 at 10:34
  • If there aren't answers there showing it, you can post it on the other question. The point is to put the answers to the issue in one place. :-) – T.J. Crowder Jan 23 '22 at 10:34
  • 2
    (You can also do `console.log(...response.headers);` Or [this](https://stackoverflow.com/a/68647698/157247).) – T.J. Crowder Jan 23 '22 at 10:41
  • Okay thank you! I have voted to close this, and marked it as duplicate. – run_the_race Jan 23 '22 at 13:02