「今天後端不再回傳假資料,而是直接去 OpenWeather API 拿即時天氣。從這一步開始,你的天氣小工具就真正能顯示即時資訊了!」
內容重點:
程式說明:
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=zh_tw`;
const response = await fetch(url);
const data = await response.json();
if (data.cod !== 200) return res.json({ error: "找不到城市或 API 錯誤" });
res.json({
name: data.name,
temp: data.main.temp,
description: data.weather[0].description,
icon: data.weather[0].icon
});
解析:串接第三方 API,後端整理資料後回傳給前端。