<JavaScript> 웹 API 소개: Fetch, LocalStorage, Geolocation 등

반응형

JavaScript에서는 개발을 보다 쉽게 만들어주는 여러 가지 API가 있습니다.

이번에는 Fetch, LocalStorage, Geolocation 등 다양한 웹 API를 소개하고 사용법을 알아보겠습니다.

 

데이터 가져오기: Fetch API

 

Fetch API는 웹에서 데이터를 가져오거나 전송하는 상황에서 유용한 기능을 제공합니다. 이를 통해 서버로부터 웹 페이지에 필요한 데이터를 가져올 수 있습니다.

 

다음과 같이 간단한 HTTP GET 요청을 Send할 수 있습니다.

 

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

 

POST 요청으로 데이터를 서버에 전송하는 예제입니다.

 

const postData = {
  key1: "value1",
  key2: "value2"
};

fetch("https://api.example.com/submit", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(postData)
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

 

로컬 데이터 저장소 활용하기: LocalStorage와 SessionStorage

LocalStorage와 SessionStorage는 브라우저에 간단한 데이터를 저장하고 가져오는 기능을 제공합니다. LocalStorage 저장소의 데이터는 만료 시간이 없으며, 사용자가 브라우저 캐시를 지우지 않는 한 계속 유지됩니다. 반면, SessionStorage 저장소의 데이터는 세션이 종료되면 삭제됩니다.

 

localStorage에 데이터를 저장하는 방법.

 

localStorage.setItem("name", "John");

 

localStorage에서 데이터를 가져오는 방법.

 

const name = localStorage.getItem("name");
console.log(name); // "John"

 

sessionStorage를 사용하는 방법도 거의 동일합니다.

 

sessionStorage.setItem("session-id", "123456");
const sessionId = sessionStorage.getItem("session-id");
console.log(sessionId); // "123456"

 

위치 정보 활용하기: Geolocation API

 

Geolocation API를 사용하면 사용자의 현재 위치 정보를 가져올 수 있습니다. 참고로 이 기능을 사용하기 전에 사용자의 위치 정보 사용 권한을 반드시 요청해야 합니다.

아래는 Geolocation API를 사용해 현재 위치의 위도와 경도를 가져오는 예제입니다.

 

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(position => {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    console.log("Latitude:", latitude, "Longitude:", longitude);
  });
} else {
  console.error("Geolocation is not supported in this browser.");
}

 

이번 글에서는 개발을 편리하게 해주는 다양한 JavaScript 웹 API에 대해 알아봤습니다.

Fetch를 이용해 데이터를 가져오고, LocalStorage와 SessionStorage로 데이터를 저장하며, Geolocation API로 위치 정보를 활용하는 방법에 대해 간단하게 알아봤습니다.

 

감사합니다.

Designed by JB FACTORY