12

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Jorge Rodríguez
  • 347
  • 2
  • 5
  • 17
  • 1
    If you use something like `headers.get('Content-Type');` does it return the value you want? – scunliffe May 28 '18 at 17:13
  • Are you in control of the server API? It looks like the server itself isn't setting any headers on the response. Can you double check using something like Postman or similar `HTTP` client that the server definitely returns headers? – Stefan Bobev May 28 '18 at 17:13

4 Answers4

9

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.

alegria
  • 931
  • 2
  • 10
  • 25
5

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)))
  }
};
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
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.

Adam
  • 4,445
  • 1
  • 31
  • 49
2

Try using this instead:

response.headers.get('x-auth-token')
Malekai
  • 4,765
  • 5
  • 25
  • 60
Nitin Jadhav
  • 6,495
  • 1
  • 46
  • 48