iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
Modern Web

AI × Web:生活魔法方程式系列 第 19

Day19.串接 OpenWeather API

  • 分享至 

  • xImage
  •  

「今天後端不再回傳假資料,而是直接去 OpenWeather API 拿即時天氣。從這一步開始,你的天氣小工具就真正能顯示即時資訊了!」

內容重點

  • 使用 fetch 呼叫 OpenWeather API
  • 處理 API key、城市名稱
  • 回傳 JSON(name, temp, description, icon)

程式說明

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,後端整理資料後回傳給前端。


上一篇
Day18.後端 API 雛形
系列文
AI × Web:生活魔法方程式19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言