Search code examples
javascriptpromisefetch

Node-fetch Promise response property prints as undefined


I know similar questions have been asked a bunch (see here and here), but I've tried the solutions mentioned there I'm trying to figure out why my node-fetch response isn't behaving as expected. Here's a simple version of the code:

 fetch(new URL("https://www.stackoverflow.com")).then(theResponse =>{
      console.log("This prints OK: "); 
      console.log(theResponse.headers);
      console.log("But this prints as undefined:");
      console.log(theResponse.headers["content-encoding"]);
      return theResponse;
})

The headers as printed are:

{
'accept-ranges': 'bytes',
'cache-control': 'private',
 connection: 'close',
'content-encoding': 'gzip',
 'content-security-policy': "upgrade-insecure-requests; frame-ancestors 'self' https://stackexchange.com",
etc.
}

Why is theResponse.headers["content-encoding"] returning as undefined?


Solution

  • You need to use the .get method of the Headers object:

    console.log(theResponse.headers.get("Content-Encoding"));
    

    Notice that unlike a Map or object property access, it works case-insensitively.