How to get content-type from the response headers with Fetch
Asked Answered
L

1

6

I'm trying to access the returned content-type from my GET request so I can decide the kind of preview I want to like for html maybe pass through an iframe and for a PDF maybe some viewer. The problem is when I do console.log(response.headers) the object returned doesn't have content-type in it but when I check the networks tab the response headers has content-type:html/text. How can I get the content-type from the response headers? this is how my GET request looks like

const getFile = async () => {
    var requestOptions = {
      method: "GET",
      headers: context.client_header,
      redirect: "follow",
    };
    let statusID = context.currentStatus.ApplicationID;
    var response = await fetch(
      process.env.REACT_APP_API_ENDPOINT +
        "/services/getStatus?ApplicationID=" +
        statusID,
      requestOptions
    );

    console.log(response.headers);

    if (response.ok) {
      let fileHtml = await response.text();
      setfileURL(fileHtml);
    } else {
      alert.show("Someting went wrong");
    }
  };
Lavena answered 4/6, 2021 at 4:52 Comment(0)
Q
17

The Headers object isn't a great candidate for console.log() since it is not easily serialisable.

If you want to see everything in it, try breaking it down to its entries via spread syntax

console.log(...response.headers)

You'll probably find that you can in fact access what you want via

response.headers.get("content-type")

See Headers.get()

Quoit answered 4/6, 2021 at 5:0 Comment(1)
response.headers.get("content-type") worked! Thanks!Lavena

© 2022 - 2024 — McMap. All rights reserved.