Bỏ qua, tới nội dung chính

Thứ Bảy, 28 tháng 11, 2026

Xây REST API với Node.js và Express 5

Một API backend cơ bản cần nhận request, kiểm tra dữ liệu, xử lý nghiệp vụ và trả response có cấu trúc. Trong bài này, chúng ta xây dựng một REST API quản lý sản phẩm bằng Node.js và Express 5. Mục tiêu không phải tạo một hệ thống production hoàn chỉnh, mà hiểu rõ request đi qua ứng dụng như thế nào và biết cách mở rộng sang database ở bước tiếp theo.

Sơ đồ request đi qua middleware, router, handler, response và error middleware
Sơ đồ vòng đời request trong một ứng dụng Express.

1. Chuẩn bị môi trường

Express 5 yêu cầu Node.js 18 trở lên. Hãy kiểm tra phiên bản Node và npm:

node -v
npm -v

Tạo project và cài Express:

mkdir express-products-api
cd express-products-api
npm init -y
npm pkg set type=module
npm install express

Lệnh npm pkg set type=module khai báo project dùng ECMAScript Modules, vì vậy ta có thể viết import thay cho require. Tạo file server.js.

2. Viết server và middleware đọc JSON

import express from 'express';

const app = express();
const PORT = 3000;

// Đọc JSON body gửi lên từ client.
app.use(express.json());

app.listen(PORT, () => {
  console.log(`API is running at http://localhost:${PORT}`);
});

express() tạo ứng dụng. express.json() là middleware đọc request body dạng JSON và gắn dữ liệu đã parse vào req.body. Middleware phải được đăng ký trước những route cần đọc body. Chưa gọi app.listen() ở bước này; ta sẽ gọi sau khi đã đăng ký đầy đủ route và middleware ở cuối file.

3. Tạo dữ liệu mẫu và endpoint GET

Để tập trung vào HTTP và routing, ta lưu dữ liệu trong một array ở bộ nhớ:

const products = [
  { id: 1, name: 'Mechanical Keyboard', price: 1200000 },
  { id: 2, name: 'Wireless Mouse', price: 450000 },
];

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

app.get('/api/products/:id', (req, res) => {
  const id = Number(req.params.id);
  const product = products.find(item => item.id === id);

  if (!product) {
    return res.status(404).json({ message: 'Product not found' });
  }

  return res.status(200).json(product);
});

Route /api/products/:id có một route parameter tên id. Express đưa giá trị URL vào req.params.id dưới dạng chuỗi, vì vậy ta chuyển sang number trước khi so sánh với ID số trong dữ liệu.

4. Tạo endpoint POST và validate input

app.post('/api/products', (req, res) => {
  const { name, price } = req.body;

  if (typeof name !== 'string' || name.trim().length === 0) {
    return res.status(400).json({ message: 'name is required' });
  }

  if (typeof price !== 'number' || price <= 0) {
    return res.status(400).json({ message: 'price must be a positive number' });
  }

  const nextId = Math.max(0, ...products.map(item => item.id)) + 1;
  const product = {
    id: nextId,
    name: name.trim(),
    price,
  };

  products.push(product);
  return res.status(201).json(product);
});

Request thành công tạo resource nên trả HTTP 201 Created. Dữ liệu người dùng gửi lên không được mặc định là hợp lệ: kiểm tra kiểu, giá trị rỗng và business rule trước khi lưu.

5. Cập nhật và xóa resource

app.patch('/api/products/:id', (req, res) => {
  const id = Number(req.params.id);
  const product = products.find(item => item.id === id);

  if (!product) {
    return res.status(404).json({ message: 'Product not found' });
  }

  const { name, price } = req.body;

  if (name !== undefined) {
    if (typeof name !== 'string' || name.trim().length === 0) {
      return res.status(400).json({ message: 'name is invalid' });
    }
    product.name = name.trim();
  }

  if (price !== undefined) {
    if (typeof price !== 'number' || price <= 0) {
      return res.status(400).json({ message: 'price is invalid' });
    }
    product.price = price;
  }

  return res.status(200).json(product);
});

app.delete('/api/products/:id', (req, res) => {
  const id = Number(req.params.id);
  const index = products.findIndex(item => item.id === id);

  if (index === -1) {
    return res.status(404).json({ message: 'Product not found' });
  }

  products.splice(index, 1);
  return res.status(204).send();
});

Dùng PATCH khi cập nhật một phần resource. Dùng DELETE để xóa. Với response 204 No Content, server không gửi JSON body.

6. Xử lý route không tồn tại và lỗi tập trung

// Đặt sau tất cả route để bắt URL không khớp.
app.use((req, res) => {
  res.status(404).json({ message: 'Route not found' });
});

// Error-handling middleware có đủ 4 tham số.
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ message: 'Internal server error' });
});

Thứ tự đăng ký middleware rất quan trọng. Route 404 đặt sau các route chính; error middleware đặt cuối. Trong Express 5, Promise bị reject hoặc lỗi throw trong async route handler sẽ tự động được chuyển tới next và đi vào error middleware nếu chưa được xử lý.

7. Chạy và kiểm tra API

Thêm đoạn sau vào cuối file server.js, sau các route, middleware 404 và error handler:

app.listen(PORT, () => {
  console.log(`API is running at http://localhost:${PORT}`);
});

Sau đó khởi động server:

node server.js

Mở terminal khác để kiểm tra danh sách sản phẩm:

curl http://localhost:3000/api/products

Tạo sản phẩm mới:

curl -X POST http://localhost:3000/api/products \
  -H "Content-Type: application/json" \
  -d '{"name":"USB-C Hub","price":790000}'

Cập nhật sản phẩm ID 1:

curl -X PATCH http://localhost:3000/api/products/1 \
  -H "Content-Type: application/json" \
  -d '{"price":1100000}'

Xóa sản phẩm ID 2:

curl -X DELETE http://localhost:3000/api/products/2

8. Cấu trúc hiện tại có giới hạn gì?

Dữ liệu đang nằm trong array nên sẽ mất khi restart server; nhiều process cũng không chia sẻ cùng một bản dữ liệu. Đây chỉ là ví dụ học routing. Khi phát triển ứng dụng thật, hãy tách route/controller/service/repository theo độ phức tạp, dùng database, validate schema (ví dụ Zod/Joi), authentication/authorization, logging, rate limiting và quản lý secrets qua environment variables. Đừng coi ví dụ CRUD trong bộ nhớ là backend production.

Kết luận

Một API Express có thể hiểu qua bốn khối: middleware chuẩn bị request, router chọn endpoint, handler xử lý use case và response trả status/body. Khi nắm luồng này, việc bổ sung database hoặc tách controller/service sẽ dễ dàng hơn nhiều.

Nguồn tham khảo

Share:

0 comments:

Đăng nhận xét