william
william

Reputation: 7664

Missing headers in Fetch response

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

Upvotes: 50

Views: 51031

Answers (6)

undefined
undefined

Reputation: 1100

Another option is to use Object.fromEntries(), for instance, Object.fromEntries(response.headers) or Object.fromEntries(response.headers.entries()). This method transforms a list of key-value pairs into an object.

fetch("https://www.google.com").then(response => console.log(Object.fromEntries(response.headers)))
//-> Promise <pending>

// console.log output:
{
    "alt-svc": "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"",
    "bfcache-opt-in": "unload",
    "cache-control": "private, max-age=0",
    "content-encoding": "br",
    "content-length": "41556",
    "content-security-policy": "upgrade-insecure-requests",
    "content-type": "text/html; charset=UTF-8",
    "date": "Wed, 04 Aug 2021 08:09:30 GMT",
    "expires": "-1",
    "server": "gws",
    "strict-transport-security": "max-age=31536000",
    "x-frame-options": "SAMEORIGIN",
    "x-xss-protection": "0"
}

Upvotes: 4

Welcor
Welcor

Reputation: 3073

this one from another answer here spams my console with duplicates of the .headers content:

response.headers.forEach(console.log)

But this one works, it creates a map:

console.log(...response.headers)

or for a better readable console output check this answer: https://stackoverflow.com/a/70821115/4394435

Upvotes: 2

Carlos Verdes
Carlos Verdes

Reputation: 3147

Although the correct answer is the one from @AndyTheEntity for me is a little bit incomplete.

CORS requests have limitations and show only a subset of headers:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

In order to show more headers on the response, the server has to add a header to allow more extra headers.

For example, after a POST request if a new resource is created you should return a 201 CREATED response and add a Location header. If you need to accept CORS also you need to add the next headers (on the server response):

Location: $url-of-created-resource
Access-Control-Expose-Headers: Location

With this you will see on the client the header Location.

If you need to send an specific header (like a SESSION_ID), then you need to add the next header in the request:

Access-Control-Request-Headers: SESSION_ID
SESSION_ID: $current_session_id

I hope this cover all needs to handle request/response using CORS.

Upvotes: 45

AndyTheEntity
AndyTheEntity

Reputation: 4136

Headers are limited for CORS requests. See https://stackoverflow.com/a/44816592/2047472

(Use access-control-expose-headers to allow exposing headers to requests from a different origin.)

Upvotes: 110

Vijay kumar Pendem
Vijay kumar Pendem

Reputation: 181

To get a specific header property you can use the following:

response.headers.get(yourProperty)

Upvotes: 18

ccnokes
ccnokes

Reputation: 7105

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

Upvotes: 99

Related Questions