最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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");
    }
  };
Share Improve this question edited Jun 4, 2021 at 5:01 Phil 165k25 gold badges261 silver badges267 bronze badges asked Jun 4, 2021 at 4:52 CassandraCassandra 2172 gold badges4 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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

发布评论

评论列表(0)

  1. 暂无评论