前六天都是讀取資料,今天讓新增按鈕真正發揮作用,資料可以從前端送到後端存起來。
今天做的事
先在最上面加入解析body的Middleware:
app.use(express.json());
接著寫新增待辦事項的路由:
app.post('/api/todos', (req, res) => {
const newTodo = {
id: todos.length > 0 ? todos[todos.length - 1].id + 1 : 1,
title: req.body.title,
done: false
};
todos.push(newTodo);
res.status(201).json(newTodo);
});
用Thunder Client送出測試請求,Body帶{"title": "測試新增的代辦事項"},收到201狀態碼跟自動產生id的新物件,確認API本身沒問題後,再回頭把新增按鈕接上:
document.querySelector('.add-box button').addEventListener('click', () => {
const input = document.querySelector('.add-box input');
const title = input.value.trim();
if (!title) return;
fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title })
})
.then(res => res.json())
.then(newTodo => {
const li = document.createElement('li');
li.textContent = newTodo.title;
document.getElementById('todo-list').appendChild(li);
input.value = '';
});
});
在畫面上輸入文字案新增,清單立刻多一筆,輸入框也自動清空。
觀察
卡關
打完程式碼要用Thunder Client測試時,沒有先啟動伺服器就直接測試了,所以一直得到ERROR,並沒有得到201跟回應的內容,後來執行了node server.js,才有看到回傳201及JSON文字。
心得
先用Thunder Client單獨測API,再接前端,這個順序讓除錯輕鬆許多,因為如果兩邊一起寫、一起測,出錯了完全不知道問題在前端還是後端。
目前新增的資料一樣只存在記憶體陣列裡,重啟伺服器就會消失,這個限制感覺越來越明顯,之後接上資料庫應該會直觀理解為什麼真正上線的網站都要用資料庫。