Missing headers in Fetch response

william picture william · Jan 24, 2018 · Viewed 14.5k times · Source

I need to make a CORS post request. I need to use fetch because axios's response is already processed to json.

But in fetch response, the headers is empty. But I don't think this is the server problem since axios response headers have the values that I want.

Any trick?

    fetch('http://localhost:9876/test/sample-download', {
        method: 'post',
        headers: {},
        body: {}
    })
        .then(response => {
            console.log(response);
        })
        .catch(err => console.error(err));

    axios.post('http://localhost:9876/test/sample-download', {}, {})
        .then(response => console.log(response))
        .catch(error => console.error(error));

Answer

ccnokes picture ccnokes · Jan 24, 2018

The Headers class instance that fetch returns is an iterable, as opposed to a plain object like axios returns. Some iterable's data, such as Headers or URLSearchParams, aren't viewable from the console, you have to iterate it and console.log each element, like:

fetch('http://localhost:9876/test/sample-download', {
    method: 'post',
    headers: {},
    body: {}
})
.then(response => {
  // Inspect the headers in the response
  response.headers.forEach(console.log);
  // OR you can do this
  for(let entry of response.headers.entries()) {
    console.log(entry);
  }
})
.catch(err => console.error(err));