【问题标题】:How to get content-type from the response headers with Fetch如何使用 Fetch 从响应标头中获取内容类型
【发布时间】:2021-08-22 04:16:58
【问题描述】:

我正在尝试从我的GET 请求中访问返回的content-type,以便我可以决定我想要的html 的预览类型可能会通过iframe,而对于PDF 可能会通过一些查看器。问题是当我执行console.log(response.headers) 时,返回的对象中没有内容类型,但是当我检查网络选项卡时,响应标头有内容类型:html/text。如何从响应标头中获取内容类型? 这就是我的 GET 请求的样子

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

【问题讨论】:

    标签: javascript get fetch-api response-headers


    【解决方案1】:

    Headers 对象不是console.log() 的理想候选对象,因为它不容易序列化。

    如果您想查看其中的所有内容,请尝试通过扩展语法将其分解为条目

    console.log(...response.headers)
    

    您可能会发现实际上您可以通过以下方式访问您想要的内容

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

    Headers.get()

    【讨论】:

    • response.headers.get("content-type") 工作!谢谢!
    猜你喜欢
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2011-05-02
    • 2011-09-30
    • 2020-11-20
    • 2017-09-06
    • 2020-02-24
    相关资源
    最近更新 更多