@exxagw

Как получить headers в fetch?

fetch(url)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
      })


каким образом получить headers в "последнем" then (responseData)?
  • Вопрос задан
  • 588 просмотров
Решения вопроса 2
alexey-m-ukolov
@alexey-m-ukolov Куратор тега JavaScript
Более красивого способа, к сожалению, нет:
let globalResponse;
fetch(url)
      .then((response) => {
            globalResponse = response;
            return response.json();
      })
      .then((responseData) => {
            console.log(responseData, globalResponse);
      })


Но можно использовать async/await:
const response = await fetch(url);
const responseData = await response.json();
console.log(responseData, response.headers);
Ответ написан
0xD34F
@0xD34F Куратор тега JavaScript
fetch(url)
  .then(r => r.json().then(data => ({ data, headers: r.headers })))
  .then(r => console.log(r.data, r.headers));
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
vahe_2000
@vahe_2000
jsfiddle

fetch("https://jsonplaceholder.typicode.com/albums")
  .then(response => {
    console.log(response.headers.get("Content-Type")); // application/json; charset=utf-8
    console.log(response.status); // 200

    return response.json();
  })
  .then(res => {
    console.log(res); // iliakan
  })
  .catch(console.log);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы