Skip to content
Advertisement

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

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement