LukasMac
LukasMac

Reputation: 898

How to read headers in body/response promise

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

Upvotes: 3

Views: 6435

Answers (1)

Ygalbel
Ygalbel

Reputation: 5519

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.

Upvotes: 4

Related Questions