Sometimes you may need to use response headers in JavaScript. How you get these headers depends on whether you’re using XHR, Fetch, or a JavaScript library.
Regardless of the method used, you will only see a subset of the response headers. This is because browsers don’t let us access unsafe headers.
Here’s a list of safe headers:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
We can only access unsafe headers if the server lets us. You can see the allowed headers through the Access-Control-Expose-Headers header (view this in the devtools).
Getting headers with XHR
You can use getAllResponseHeaders to get all response headers. These headers will be in the form of a string (which is not very usable).
request.addEventListener('load', e => {
const headers = request.getAllResponseHeaders()
console.log(headers)
})
To get one specific header, you can use getResponseHeader.
This approach can feel weird because we’re sending an array into the second then call.
A better approach is to call the json method first, then send headers over in the then call after the json gets parsed successfully. We can even provide more information if we want.
fetch('https://api.github.com/users/zellwk/repos')
.then(r => {
const headers = Array.from(r.headers.entries())
.reduce((accumulator, [header, value]) => {
return Object.assign({}, accumulator, {
[header]: value
})
}, {})
return r.json()
.then(body => ({ headers, body }))
})
.then(response => {
console.log(response.headers) // the headers
console.log(response.body) // the body
})
Getting headers with zlFetch
zlFetch provides you with response headers in your first then call.
zlFetch('https://api.github.com/users/zellwk/repos')
.then(response => {
console.log(response.headers) // the headers
console.log(response.body) // the body
})
Exercise
Request for a list of my repositories from Github
Get the link header with XHR
Get the link header with Fetch
Get the link header in the second then call when you use Fetch