「畫面有了,但沒有資料就像蓋房子沒水電。今天我們用 Node.js + Express 建立一個簡單的後端 API,先回傳假資料,讓前端可以抓到資料並顯示。這也是學習前後端分工的第一步!」
內容重點:
/weather
API,先回傳假資料/weather
,確認能拿到資料程式說明:
app.get("/weather", (req, res) => {
res.json({
name: req.query.city || "Taipei",
temp: 25,
description: "晴天",
icon: "01d"
});
});
const res = await fetch(`/weather?city=${city}`);
const data = await res.json();
解析:先建立前後端溝通流程,確保前端 fetch 後能拿到資料。