Trung BìnhNode.js iconNode.js

REST API trong Express: cách định nghĩa các HTTP methods?

Express map trực tiếp tới HTTP methods với semantics rõ ràng: GET (idempotent, safe — chỉ đọc, không side effects), POST (không idempotent — tạo resource mới, mỗi call tạo record mới), PUT (idempotent — replace toàn bộ resource, gửi thiếu field thì field đó bị null/default), PATCH (idempotent — partial update, chỉ gửi fields cần thay đổi), DELETE (idempotent — xóa, gọi nhiều lần kết quả như nhau).

  • CRUD thực tế: GET /users (list), POST /users (create, trả 201), GET /users/:id (read), PUT /users/:id (replace, trả 200), PATCH /users/:id (update, trả 200), DELETE /users/:id (delete, trả 204 no content).
  • Status codes quan trọng: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 500 Internal Server Error.
  • Content negotiation: req.accepts('json') kiểm tra client Accept header.

Pitfall: dùng GET với body để filter — không đúng semantics, dùng query params thay thế.

Xem toàn bộ Node.js cùng filter theo level & chủ đề con.

Mở danh sách Node.js