Cơ BảnNode.js iconNode.js

Cách tạo HTTP server với module http trong Node.js?

Module http là built-in, không cần cài thêm: const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true })); }); server.listen(3000). req chứa method, url, headers và là Readable stream (đọc body qua req.on('data', chunk => ...)). res là Writable stream — phải gọi res.end() để kết thúc, không thì client treo mãi.

  • Trong thực tế hiếm ai dùng http module trực tiếp vì rất verbose — Express, Fastify, Hono wrap lại với routing, middleware, body parsing tiện hơn nhiều.
  • Tuy nhiên hiểu http module giúp debug networking issues và hiểu cách các framework hoạt động bên dưới.

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

Mở danh sách Node.js