建立 HTTP 伺服器#
Node.js 內建 http 模組,讓你不需要安裝任何套件就能建立 HTTP 伺服器,這也是 Node.js 最核心的應用場景之一。
1. 建立最簡單的伺服器#
1
2
3
4
5
6
7
8
9
10
| const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Hello World!");
});
server.listen(3000, () => {
console.log("伺服器啟動於 http://localhost:3000");
});
|
執行後,開啟瀏覽器前往 http://localhost:3000,即可看到 Hello World!。
req(IncomingMessage):請求物件,包含 URL、方法、標頭、請求主體等資訊。res(ServerResponse):回應物件,用於設定狀態碼、標頭、回應內容。res.writeHead():設定 HTTP 狀態碼與回應標頭。res.end():結束回應並傳送內容。
2. 根據路由回傳不同內容#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| const http = require("http");
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
res.setHeader("Content-Type", "application/json; charset=utf-8");
if (url === "/" && method === "GET") {
res.writeHead(200);
res.end(JSON.stringify({ message: "首頁" }));
} else if (url === "/about" && method === "GET") {
res.writeHead(200);
res.end(JSON.stringify({ message: "關於我們" }));
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: "找不到頁面" }));
}
});
server.listen(3000, () => {
console.log("伺服器啟動於 http://localhost:3000");
});
|
3. 處理 POST 請求(接收請求主體)#
HTTP 請求主體(body)是以資料流(stream)的方式接收,需要監聽 data 和 end 事件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/data") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
const parsed = JSON.parse(body);
console.log("收到資料:", parsed);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ received: parsed }));
});
} else {
res.writeHead(404);
res.end("Not Found");
}
});
server.listen(3000, () => {
console.log("伺服器啟動於 http://localhost:3000");
});
|
4. 回傳 HTML 頁面#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| const http = require("http");
const fs = require("fs/promises");
const path = require("path");
const server = http.createServer(async (req, res) => {
if (req.url === "/" && req.method === "GET") {
try {
const html = await fs.readFile(
path.join(__dirname, "index.html"),
"utf8"
);
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(html);
} catch (err) {
res.writeHead(500);
res.end("Internal Server Error");
}
}
});
server.listen(3000);
|
5. 常用 HTTP 狀態碼#
| 狀態碼 | 說明 |
|---|
| 200 | OK,請求成功 |
| 201 | Created,資源建立成功 |
| 400 | Bad Request,請求格式錯誤 |
| 401 | Unauthorized,未授權 |
| 403 | Forbidden,禁止存取 |
| 404 | Not Found,找不到資源 |
| 500 | Internal Server Error,伺服器內部錯誤 |
6. 小結#
原生 http 模組功能完整,但路由管理較繁瑣。實際開發中通常會使用 Express 等框架來簡化伺服器開發,將在下一章介紹。
Reference#