[javascript] 비동기 데이터 요청을 이용한 날씨 정보 확인
웹 애플리케이션을 개발할 때, 데이터를 서버에서 비동기적으로 요청하고 처리하는 과정은 매우 일반적입니다. 이 글에서는 JavaScript를 사용하여 비동기 데이터 요청을 수행하고, 그 결과를 화면에 표시하는 방법을 알아보겠습니다.
1. XMLHttpRequest를 이용한 데이터 요청
가장 기본적인 방법은 XMLHttpRequest
객체를 사용하여 서버로 데이터를 요청하는 것입니다. 아래는 XMLHttpRequest
를 사용하여 OpenWeatherMap의 API를 이용하여 날씨 정보를 가져오는 예제 코드입니다.
let request = new XMLHttpRequest();
const apiKey = 'your_api_key';
const city = 'Seoul';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
let data = JSON.parse(request.responseText);
// 데이터 활용 로직
} else {
console.error('데이터를 불러오는 중에 오류가 발생했습니다.');
}
};
request.send();
2. Fetch API를 이용한 데이터 요청
XMLHttpRequest
대신에 최신의 Fetch API
를 사용하여 동일한 요청을 수행할 수도 있습니다.
const apiKey = 'your_api_key';
const city = 'Seoul';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('데이터를 불러오는 중에 오류가 발생했습니다.');
}
return response.json();
})
.then(data => {
// 데이터 활용 로직
})
.catch(error => {
console.error(error);
});
3. Axios를 이용한 데이터 요청
Axios
는 더 간편한 API 요청을 위해 자주 사용되는 라이브러리 중 하나입니다.
const axios = require('axios');
const apiKey = 'your_api_key';
const city = 'Seoul';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
axios.get(url)
.then(response => {
// 데이터 활용 로직
})
.catch(error => {
console.error('데이터를 불러오는 중에 오류가 발생했습니다.');
});
이제 비동기 데이터 요청을 통해 서버에서 날씨 정보를 가져와 화면에 표시하는 방법을 알아보았습니다. 각각의 방법은 장단점이 있으니 상황에 맞게 선택하여 사용하시면 됩니다.
참고자료: