简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM