Jorge Rodríguez
Jorge Rodríguez

Reputation: 427

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?

Upvotes: 16

Views: 13893

Answers (4)

Adam
Adam

Reputation: 4683

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.

Upvotes: 8

Nitin Jadhav
Nitin Jadhav

Reputation: 7286

Try using this instead:

response.headers.get('x-auth-token')

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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)))
  }
};

Upvotes: 5

alegria
alegria

Reputation: 1145

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.

Upvotes: 9

Related Questions