JavaScript
Fetch (3) - 날씨 api 가져와서 쓰기
우영11
2023. 6. 30. 22:21
Fetch를 사용하는 목적은 다른 공공데이터를 가져오는것에 있다.
https://github.com/robertoduessmann/weather-api
GitHub - robertoduessmann/weather-api: A RESTful API to check the weather
A RESTful API to check the weather. Contribute to robertoduessmann/weather-api development by creating an account on GitHub.
github.com
위 사이트에서
https://goweather.herokuapp.com/weather/{city}
형태로 {city}의 현재 날씨 정보를 가져올 수 있다.
소스를 확인해 보면 다음과 같다.
{
"temperature": "+30 °C",
"wind": "13 km/h",
"description": "Partly cloudy",
"forecast": [
{
"day": "1",
"temperature": "29 °C",
"wind": "12 km/h"
},
{
"day": "2",
"temperature": "+24 °C",
"wind": "8 km/h"
},
{
"day": "3",
"temperature": "+27 °C",
"wind": "15 km/h"
}
]}
JSON 형태로 저장 되 있으니 우리는 쉽게 정보를 가지고 올 수 있다.
let city=document.querySelector("#city").value
fetch("https://goweather.herokuapp.com/weather/"+city)
.then(function(response){
return response.json();
})
.then(function(data){
// alert(data.temperature);
let disp=document.querySelector("#disp");
disp.innerText=data.temperature;
})
.catch(function(error){
document.write("실패---", error);
});
input박스로 지역명 값을 받아서 자동으로 데이터를 가져오는 코드이다.