DEV Community

Sean Brunnock
Sean Brunnock

Posted on • Edited on

Express devs and WHATWG editors have very different ideas about accessing headers.

I did what I thought would be an easy project. Oh, how wrong I was.

I had an ERN (Express/React/Node) app that simply printed the HTTP headers that your browser sent to my server. I thought it would be a simple matter to also show the HTTP headers that your browser received from my server. It turns out that this list of headers is a very different data structure.

To access the headers on an express server, just use req.headers. It's a simple object with the expected keys and values.

The Fetch API allows your browser to access HTTP headers via response.headers. For example, you could run fetch('http://example.com/').then(response=>console.log(response.headers)). The problem is that the Fetch API returns an iterable which is very different from Express's simple object.

To render the iterable, I have to use let headersARR=[];
for (let header of [...response.headers.entries()]) {
headersArr.push(header);
}
.

I'm sure that the Express folks and the WHATWG folks have their reasons for handling HTTP headers differently. It just makes things more difficult for us mere developers.

Anyways, you can try my demo at sean.brunnock.com and view the source to see the nuts and bolts and you can visit https://developer.mozilla.org/en-US/docs/Web/API/Headers for lots more info about accessing headers with fetch.

Top comments (0)