【问题标题】:How to read headers in body/response promise如何阅读正文/响应承诺中的标题
【发布时间】:2016-09-19 06:42:46
【问题描述】:

我正在使用 fetch API 调用 API 端点。 如何在已解决的正文承诺中读取响应 bodyheaders

下面是我的代码sn-p:

  fetch(url, {
      credentials: 'include',
      method: 'post',
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      body: JSON.stringify({
        email: email,
        password: password,
      }),
    })
    .then(response => response.json())
    .then(function(response) {
      // How to access response headers here?
    });

【问题讨论】:

    标签: javascript fetch response-headers fetch-api


    【解决方案1】:

    正如 fetch documentation 中所说,您可以使用此 sn-p 获取响应标头:

      fetch(myRequest).then(function(response) {
    
      var contentType = response.headers.get("content-type");
    
      if (contentType && contentType.indexOf("application/json") !== -1) {
        return response.json().then(function(json) {
          // process your JSON further
        });
      } else {
        console.log("Oops, we haven't got JSON!");
      }
    });
    

    对于body,您会找到here 一些示例。

    【讨论】:

    • 我需要在处理 JSON 的地方获取标头。
    • 在我的示例中,您可以在 json 方法中访问 c​​ontentType
    • response.headers.get("content-type") - 这有帮助,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    相关资源
    最近更新 更多