JavaScript fetch()


개요

JavaScript fetch()

then

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((response) => response.json())
  .then((json) => {
    for (const [k, v] of Object.entries(json)) {
      console.log(k, ':', v);
    }
});
fetch('https://jsonplaceholder.typicode.com/posts?_page=1&_limit=5')
  .then(response => {
     console.log('x-total-count:', response.headers.get('x-total-count'));
     console.log('link:', response.headers.get('link'));
     return response.json();
  })
  .then((json) => {
     json.forEach(x => console.log(JSON.stringify(x)));
  })
  .catch(error => console.error(error));

await

async function fetchData() {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
      const data = await response.json();
      for (const [k, v] of Object.entries(data)) {
            console.log(k, ':', v);
      }
}
fetchData();

같이 보기

참고