Skip to main content

[Node] 使用 ChatGPT 製作 todolist API

完整程式碼: https://github.com/Stevetanus/To-do-list/tree/master/chatGPT_todolist

詠唱

Q: 我想用 NodeJS 寫一個 HTTP Server

A:

Q: 我想在 127.0.0.1 的伺服器端建立 /todos 的路徑,在 get 指令時會回傳 todos 物件的資料,post 指令時會將資料加入 todos 物件,也需要 delete 指令去刪除特定 id 的資料,關於 id 的部分,我想使用 uuid 模組,最後,我會需要 patch 指令去修改特定 id 的資料

A:

const http = require("http");
const { v4: uuidv4 } = require("uuid");

const hostname = "127.0.0.1";
const port = 3000;

const todos = {};

const server = http.createServer((req, res) => {
const { method, url } = req;

if (url === "/todos") {
switch (method) {
case "GET":
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(todos));
break;
case "POST":
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
const id = uuidv4();
const todo = JSON.parse(body);
todos[id] = todo;
res.statusCode = 201;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ id, ...todo }));
});
break;
case "DELETE":
const deleteId = url.split("/")[2];
delete todos[deleteId];
res.statusCode = 204;
res.end();
break;
case "PATCH":
let patchBody = "";
req.on("data", (chunk) => {
patchBody += chunk.toString();
});
req.on("end", () => {
const patchId = url.split("/")[2];
const patchData = JSON.parse(patchBody);
todos[patchId] = { ...todos[patchId], ...patchData };
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(todos[patchId]));
});
break;
default:
res.statusCode = 405;
res.end();
break;
}
} else {
res.statusCode = 404;
res.end();
}
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Q: 請幫我加上 handleError.js 來去處理常見的錯誤狀況與輸入檢查

A:

handleError.js