Missing headers in Fetch response
The Headers class instance that fetch returns is an iterable, as opposed to a plain object like axios returns. Some iterable's data, such as Headers or URLSearchParams, aren't viewable from the console, you have to iterate it and console.log each element, like:
fetch('http://localhost:9876/test/sample-download', {
method: 'post',
headers: {},
body: {}
})
.then(response => {
// Inspect the headers in the response
response.headers.forEach(console.log);
// OR you can do this
for(let entry of response.headers.entries()) {
console.log(entry);
}
})
.catch(err => console.error(err));
Headers are limited for CORS requests. See https://stackoverflow.com/a/44816592/2047472
(Use access-control-expose-headers
to allow exposing headers to requests from a different origin.)
To get a specific header property you can use the following:
response.headers.get(yourProperty)
Although the correct answer is the one from @AndyTheEntity for me is a little bit incomplete.
CORS requests have limitations and show only a subset of headers:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
In order to show more headers on the response, the server has to add a header to allow more extra headers.
For example, after a POST request if a new resource is created you should return a 201 CREATED response and add a Location
header.
If you need to accept CORS also you need to add the next headers (on the server response):
Location: $url-of-created-resource
Access-Control-Expose-Headers: Location
With this you will see on the client the header Location
.
If you need to send an specific header (like a SESSION_ID
), then you need to add the next header in the request:
Access-Control-Request-Headers: SESSION_ID
SESSION_ID: $current_session_id
I hope this cover all needs to handle request/response using CORS.