在前幾天的文章中,我們已經能透過 API 讀取資料,今天要把功能補齊,做出一個完整的 CRUD API :
在 RESTful API 中,通常這樣對應:
操作 | HTTP 方法 | 範例路由 |
---|---|---|
建立 Create | POST | POST /api/todos |
讀取 Read | GET | GET /api/todos 、GET /api/todos/:id |
更新 Update | PUT / PATCH | PUT /api/todos/:id |
刪除 Delete | DELETE | DELETE /api/todos/:id |
在 index.js 中加入以下程式碼:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
// 模擬資料庫
let todos = [
{ id: 1, task: '學習 API 基礎', done: true },
{ id: 2, task: '撰寫第一個 API', done: false }
];
// ===== Create 建立資料 =====
app.post('/api/todos', (req, res) => {
const { task } = req.body;
if (!task) {
return res.status(400).json({ error: 'Task is required' });
}
const newTodo = {
id: todos.length + 1,
task,
done: false
};
todos.push(newTodo);
res.status(201).json(newTodo);
});
// ===== Read 讀取資料 =====
// 取得所有
app.get('/api/todos', (req, res) => {
res.json(todos);
});
// 取得單一
app.get('/api/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const todo = todos.find(t => t.id === id);
if (!todo) {
return res.status(404).json({ error: 'Todo not found' });
}
res.json(todo);
});
// ===== Update 更新資料 =====
app.put('/api/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const { task, done } = req.body;
const todo = todos.find(t => t.id === id);
if (!todo) {
return res.status(404).json({ error: 'Todo not found' });
}
if (task !== undefined) todo.task = task;
if (done !== undefined) todo.done = done;
res.json(todo);
});
// ===== Delete 刪除資料 =====
app.delete('/api/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = todos.findIndex(t => t.id === id);
if (index === -1) {
return res.status(404).json({ error: 'Todo not found' });
}
const deleted = todos.splice(index, 1);
res.json(deleted[0]);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
node index.js
POST http://localhost:3000/api/todos
Body: { "task": "寫 Day 17 文章" }
GET http://localhost:3000/api/todos
GET http://localhost:3000/api/todos/1
PUT http://localhost:3000/api/todos/2
Body: { "done": true }
DELETE http://localhost:3000/api/todos/1
今天我們完成了一個 完整的 CRUD API: