When dealing with requests using Javascript, for example with the Fetch API, you may find yourself needing to deal with response headers.
Many APIs will use header information to share useful data. The WordPress API returns information like the total number of posts in a post type and the total number of pages at the current pagination sizing.
Unlike a typical JSON response, the headers aren’t immediately available on the response, which may trip you up if you’re new to the Fetch API. Let’s say your Fetch request looks like this:
fetch('//www.website.com/wp-json/wp/v2/posts?per_page=10&page=1')
.then(res => {
// do something
})
In order to access the response header ‘X-WP-TotalPages’ you would handle the response like this:
fetch('//www.website.com/wp-json/wp/v2/posts?per_page=10&page=1')
.then(res => {
// do something
totalPages = parseFloat(res.headers.get('X-WP-TotalPages'))
})
Instead of trying to access the name of the header right on the “headers” object, you have to use the get function to pull the header data.
This can be used in a variety of ways, for example making requests to any number of API’s in frontend react applications.
You can read more about request and response headers at Mozilla.org