'JS fetch, not getting headers on response
I'm making a request using fetch to wordpress api, but I get a empty headers object on the response, anyone knows why?
here's my fetch action
export const getJobs = () => {
return dispatch => {
fetch(endpoints.jobs)
.then(res => res.json())
.then(data => dispatch(setJobs(data)))
}
};
and here's the object that I get before doing res.json
body: (...)
bodyUsed: false
headers: {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "url"
any ideas on how I can get all the headers from the response?
Solution 1:[1]
There is a restriction on accessing response headers when using CORS. Since your response type is cors that might be the culprit.
See this answer for details.
Solution 2:[2]
Just because the console shows {} for headers, that doesn't necessarily mean that there aren't any accessible headers. If any were sent, they should be accessible on res.headers, which is a Headers object, which...
...allows you to perform various actions on HTTP request and response headers.
...for instance, with get.
For example, if setJobs needs the foo header:
export const getJobs = () => {
return dispatch => {
fetch(endpoints.jobs)
// Read and parse the body and then return an object with the body data and the `foo` header
.then(res => res.json().then(data => ({data, foo: res.headers.get("foo")})))
// Receive the body data and the `foo` header and pass them on to `setJobs`
.then(({data, foo}) => dispatch(setJobs(data, foo)))
}
};
Solution 3:[3]
Try using this instead:
response.headers.get('x-auth-token')
Solution 4:[4]
For me, this was a combination of the other two answers from dashboard and T.J.
On the server side, I had to add the header access-control-expose-headers to my response, with the comma-separated headers I wanted to read. See docs about access-control-expose-headers here.
But when I tried to access res.headers via console.log(JSON.stringify(res.headers), it was just outputting {}. T.J.'s solution was what worked for me, in that I had to use:
res.headers.get("header-name");
And that gave me the result I was hoping for.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alegria |
| Solution 2 | |
| Solution 3 | LogicalBranch |
| Solution 4 | Adam |
