Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
Jorge Rodríguez Avatar asked May 28 '18 17:05

Jorge Rodríguez


People also ask

How do I get response headers in Fetch?

We then fetch this request using fetch() , extract a blob from the response using Response. blob , create an object URL out of it using URL. createObjectURL , and display this in an <img> . Note that at the top of the fetch() block, we log the response headers to the console.

Can JavaScript read response headers?

Can I read response headers in JavaScript? While you can't ready any headers of HTML response in JS, you can read Server-Timing header, and you can pass arbitrary key-value data through it.

How do I view response headers?

To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.


2 Answers

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.

like image 136
alegria Avatar answered Oct 02 '22 01:10

alegria


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)))
  }
};
like image 37
T.J. Crowder Avatar answered Oct 02 '22 03:10

T.J. Crowder