fetch()함수로 API 호출하기

김기현·2021년 12월 22일
post-thumbnail

이번 포스팅에서는 원격 API를 간편하게 호출할 수 있도록 하는 fetch()함수에 대해 알아보고 weather api를 적용해보겠습니다!

원격 API 호출을 생각하면 jQuery, request와 같은 라이브러리가 생각나지만
요즘에는 라이브러리의 도움 없이도 브라우저에 내장된 fetch() 함수를 이용하면 충분합니다.

fetch() 사용방법

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => {
      weather.innerText = `Weather is ${data.weather[0].main}/${data.main.temp}`;
      city.innerText = data.name;
    })
    .catch((error) => console.log("error:", error));

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


Geolocation API, Weather API 호출하기

const API_KEY = "AAA";

function onGeoOk(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      weather.innerText = `Weather is ${data.weather[0].main}/${data.main.temp}`;
      // ARRAY의 첫번째 Element를 가져와야 하기 때문이다
      city.innerText = data.name;
    });
}

function onGeoError() {
  alert("Can't find. No weather for you");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

위 코드는 Geolocation API를 사용해 사용자의 위치를 파악한 후 Weather API로 날씨를 가져옵니다.

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

Geolocation API는 navigator.geolocation 객체를 통해 사용할 수 있습니다.

위치표현

const API_KEY = "AAA";

function onGeoOk(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
  }
  

사용자의 위치는 GeolocationPosition 객체를 담은 GeolocationCoordinates 객체를 사용하여 표현합니다.
그리고 GeolocationCoordinates 인스턴스 중 지도의 지점을 가리킬 때 latitude와 longitude로 위치를 가져옵니다.

function onGeoError() {
  alert("Can't find. No weather for you");
}

사용자의 위치를 가져오지 못하였을 때 에러처리를 합니다.

API 호출

{
  "coord": {
    "lon": 111.11
    "lat": 11.11
  },
  "weather": [
    {
      "main": "Clear",
    }
  ],
  "name": "Songjeong",
}
fetch(url)
    .then((response) => response.json())
    .then((data) => {
      weather.innerText = `Weather is ${data.weather[0].main}/${data.main.temp}`;
      // ARRAY의 첫번째 Element를 가져와야 하기 때문
      city.innerText = data.name;
    });

대부분의 REST API들은 JSON 형태의 데이터를 응답하기 때문에, response 객체는 json() 메서드를 이용합니다.
json() 메서드를 호출하면 JSON 포멧의 응답을 자바스크립트 객체로 변환화여 얻을 수 있습니다.


참고한 사이트

DaleSeo

profile
피자, 코드, 커피를 사랑하는 피코커

0개의 댓글