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?
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 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.
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.
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.
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)))
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With