Study/JavaScript

[JavaScript_study] fetch api

갈푸라떼 2022. 4. 13. 02:57

* fetch api 사용법

fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환합니다. 반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject합니다.

 

fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));

 

* fetch api 특징

  • 브라우저 api중 하나이다.
  • 비동기의 대표적인 api이다. 서버와 통신할 수 있는 api이다.
  • .json()메서드는 이름은 .json이지만 실제로는 Object로 반환해준다.
  • .json()은 Promise를 return한다.

 * fetch 예시 코드

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      fetch(
        'https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0'
      )
        .then((response) => {
          return response.json();
        })
        .then((data) => console.log(data.dataseries));
    </script>
  </body>
</html>