보여줄게: 가져오기 – 코드로 주문
지난 강의에서는 브라우저에서 API를 직접 열었어. 이제 JavaScript는 동일한 작업을 수행해.fetch명령:
const adresa = 'https://api.open-meteo.com/v1/forecast?latitude=49.19&longitude=16.61¤t_weather=true';
const odpoved = await fetch(adresa);
const data = await odpoved.json();
console.log(data.current_weather.temperature);
여기서 무슨 일이 일어나고 있는지 한 줄씩 살펴보세요.
1.fetch(adresa)– 요청을 보냅니다(웨이터가 주방으로 향해).
2.await– 기다려 다시 돌아올 때까지 기다리세요. 인터넷에는 잠시 시간이 걸립니다!
3.odpoved.json()– 응답을 JavaScript 객체로 변환해.
4. 그런 다음 일반 개체(점, 점, 완료)처럼 데이터를 사용하여 작업해.
await표시된 함수 내에서만 작동해.async, 또는<script type="module">. 브라우저에 *“await는 비동기 함수에서만 유효해.”*라는 오류가 표시되면 코드를 다음과 같이 래핑해.
async function nacti() {
// fetch and await go here
}
nacti();
페이지의 데이터를 인쇄해.
콘솔은 프로그래머를 위한 것야. 방문자는 페이지의 데이터를 보고 싶어해.
<p id="teplota">Loading…</p>
<script type="module">
const odpoved = await fetch('https://api.open-meteo.com/v1/forecast?latitude=49.19&longitude=16.61¤t_weather=true');
const data = await odpoved.json();
document.querySelector('#teplota').textContent =
`Right now it's ${data.current_weather.temperature} °C`;
</script>
Magician의 친숙한 내용(querySelector,textContent) 플러스 새로운fetch. 더 이상은 없어.
네 차례 💪
- 다음과 같은 단락을 추가해.
id="teplota"위의 스크립트를 네 웹사이트에 추가해. - 자신의 도시로 좌표를 변경해.
- 풍속도 디스플레이에 추가해(
data.current_weather.windspeed). - 보너스: 온도가 0도 이하일 때 ”🥶 Bundle up!”을 추가해. 텍스트에.
이번 수업에서 배울 점
-fetch(adresa)요청을 보내고,await응답을 기다립니다.
-.json()응답을 작업 방법을 이미 알고 있는 객체로 변환해.
- 전체 인터넷의 데이터는 이제 단 하나의 기능으로 가능해.
© 2026 Ing. Martin Polak / AlgoRhino · 콘텐츠 이용 약관