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

javascript - How to read headers in bodyresponse promise - Stack Overflow

programmeradmin1浏览0评论

I'm calling API endpoint using fetch API. How can I read response body and headers in resolved body promise?

My code snippet below:

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

I'm calling API endpoint using fetch API. How can I read response body and headers in resolved body promise?

My code snippet below:

  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?
    });
Share Improve this question edited Aug 28, 2023 at 5:56 VLAZ 29.2k9 gold badges63 silver badges84 bronze badges asked May 22, 2016 at 10:26 LukasMacLukasMac 8981 gold badge8 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

As described in the Fetch API documentation, you can get response headers with this snippet:

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

For the body you will find here some examples.

发布评论

评论列表(0)

  1. 暂无评论