Express.js: Routing, Middleware, Error Handler

Express.js คือ Web Framework สำหรับ Node.js ที่ช่วยสร้าง API ได้รวดเร็วผ่านระบบ Routing, Middleware, Router และ Error Handling Middleware

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุค Native HTTP / Low-level Server"]
    A["http.createServer
เขียน routing เอง"] end subgraph Era2["ยุค Express / Minimal Framework"] B["app.get/app.post
Routing ง่าย"] C["Middleware
งานกลาง request"] end subgraph Era3["ยุค Modular API / Scalable Express"] D["express.Router
แยก route เป็นไฟล์"] E["Error Middleware
จัดการ error กลาง"] end A --> B --> C --> D --> E

แนวคิดสำคัญ

ตาราง Express Concepts

แนวคิด หน้าที่ ตัวอย่าง
Application แอป Express หลัก express()
Route endpoint เฉพาะ app.get('/users')
Middleware งานกลาง request express.json()
Router แยก route เป็น module express.Router()
Error Handler จัดการ error กลาง (err, req, res, next)

Mermaid Diagram: Express Request Pipeline

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  A["Client Request
คำขอ"] --> B["Middleware
ตรวจ/แปลงข้อมูล"] B --> C["Router
เลือก endpoint"] C --> D["Route Handler
ทำงานหลัก"] D --> E["Response
ส่งผลลัพธ์"] D --> F["Error Handler
จัดการข้อผิดพลาด"] F --> E

Code Example

// server.mjs
// Express API พร้อม middleware, route และ error handler
import express from 'express';

const app = express();
const lessons = [{ id: 1, title: 'Node.js Runtime' }];

// built-in middleware สำหรับอ่าน JSON body
app.use(express.json());

// custom middleware สำหรับ log request
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.get('/api/lessons', (req, res) => {
  res.json(lessons);
});

app.get('/api/lessons/:id', (req, res, next) => {
  const lesson = lessons.find(item => item.id === Number(req.params.id));
  if (!lesson) {
    return next(new Error('Lesson not found'));
  }
  res.json(lesson);
});

app.post('/api/lessons', (req, res) => {
  const lesson = { id: Date.now(), title: req.body.title };
  lessons.push(lesson);
  res.status(201).json(lesson);
});

// error handling middleware ต้องมี 4 parameters
app.use((err, req, res, next) => {
  res.status(404).json({ message: err.message });
});

app.listen(3000, () => {
  console.log('API running at http://localhost:3000');
});

// ตัวอย่างการใช้งาน:
// npm install express
// node server.mjs
// GET http://localhost:3000/api/lessons

กิจกรรมท้ายบท

กลับสัปดาห์ที่ 10