如何读取正文/响应承诺中的标头



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

我的代码片段如下:

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

如 Fetch API 文档中所述,您可以使用以下代码段获取响应标头:

fetch(myRequest)
  .then((response) => {
     const contentType = response.headers.get('content-type');
     if (!contentType || !contentType.includes('application/json')) {
       throw new TypeError("Oops, we haven't got JSON!");
     }
     return response.json();
  })
  .then((data) => {
      /* process your data further */
  })
  .catch((error) => console.error(error));

对于身体,你会在这里找到一些例子。

最新更新