昨天學了 Node.js 的 Event Loop 和模組系統,今天要來挑戰更實際的東西:建立一個伺服器。
這是所有後端開發的起點,能讓程式接收使用者的請求,並回應資料。
簡單來說:
當我在瀏覽器輸入網址(例如 http://localhost:3000),瀏覽器就會對伺服器發出請求,伺服器回應一段文字或資料。
Node.js 本身就有 http 模組,可以直接建立伺服器。
import http from "http";
// 建立伺服器
const server = http.createServer((req, res) => {
  // 設定回應的 Content-Type
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
  if (req.url === "/") {
    res.end("這是首頁");
  } else if (req.url === "/about") {
    res.end("這是關於頁面");
  } else {
    res.statusCode = 404;
    res.end("找不到頁面");
  }
});
// 伺服器監聽 3000 port
server.listen(3000, () => {
  console.log("伺服器啟動:http://localhost:3000");
});
執行:
node app.js
然後在瀏覽器打開 http://localhost:3000,就會看到文字出現!
req 代表使用者送來的請求,可以看到一些資訊:
console.log(req.method); // 請求方法 (GET, POST...)
console.log(req.url);    // 請求路徑 (/、/about...)
這樣就能根據不同的請求來決定要回應什麼。
今天我做了兩個小實驗:
/ 回傳「這是首頁」,在 /about 回傳「這是關於頁面」。今天最大的收穫就是:我真的跑起了「自己的伺服器」。
雖然它很簡單,只會回傳文字,但從 http://localhost:3000 打開網頁時,看到那行字出現,真的蠻有成就感的。
另外我也發現:直接用 Node.js 的 http 模組寫路由,程式會很快變複雜。
這也是為什麼大家後來都用 Express,因為它把路由跟 Middleware 都整理得更好寫。