Home > database >  Node Fetch cannot get header value from headers object
Node Fetch cannot get header value from headers object

Time:09-04

I have some code using the node-fetch API to make an HTTP request. The code is the following:

fetch('/home.html', {
    body,
    method: 'POST',
    headers,
    withCredentials: true,
    //validateStatus: () => true,
    redirect: 'manual'
  })
    .then(resp => {console.log(resp.headers)

The bellow code when run prints an object of the HTTP response headers as follows:

{
  connection: 'close',
  'content-language': 'en-US',
  date: 'Sat, 03 Sep 2022 10:17:04 GMT',
  location: 'https://ps.asmadrid.org/public/home.html',
  server: 'PowerSchool SIS',
  'set-cookie': 'JSESSIONID=B2888D2BB22737AE7CF515048793DFB4; Path=/; Secure; HttpOnly; SameSite=None',
  'strict-transport-security': 'max-age=31536000',
  'transfer-encoding': 'chunked',
  'x-content-type-options': 'nosniff',
  'x-frame-options': 'SAMEORIGIN'
}

This is correct. But then if I change the console.log statement at the end to log the set-cookie header, it logs undefined:

// ...
    .then(resp => {console.log(resp.headers['set-cookie'])

As far as I'm aware, the node-fetch headers object is a normal object with nothing special, so why isn't this working? Why can't I get an individual header value?

CodePudding user response:

well, it's not a normal object, it's actually a class

so you need to use headers.get method:

.then(resp => {console.log(resp.headers.get('set-cookie'))

see Accessing Headers and other Metadata

or in your case, you can use headers.raw method to get an array of valuse for this specific header:

.then(resp => {console.log(resp.headers.raw()['set-cookie'])

as described here: Extract Set-Cookie Header

  • Related