Skip to content

HTTP Module

มือใหม่ควรรู้: HTTP คืออะไรและสำคัญอย่างไร?

HTTP คือโปรโตคอลหลักของโลกอินเทอร์เน็ต ทุกเว็บเบราว์เซอร์และเว็บเซิร์ฟเวอร์สื่อสารกันด้วย HTTP ถ้าอยากสร้างเว็บเซิร์ฟเวอร์หรือ API ด้วย Node.js ต้องเริ่มจาก module นี้

  • HTTP คือพื้นฐานของการสื่อสารข้อมูลบนเว็บ
  • Node.js มี http module ในตัว ทำให้สร้างเว็บเซิร์ฟเวอร์เองได้ง่ายมาก
  • มือใหม่จะเข้าใจโครงสร้าง request/response และการรับส่งข้อมูลบนเว็บ

แนะนำ HTTP module

http เป็น built-in module สำหรับสร้าง web server และ client ที่รองรับ HTTP protocol โดยตรง เหมาะสำหรับการสร้าง REST API, web server, หรือ proxy

ฟังก์ชันหลักที่ใช้บ่อย

http.createServer([requestListener])

สร้าง HTTP server

js
const http = require("http");
const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, Node.js HTTP!");
});
server.listen(3000);

http.get(options[, callback])

ส่ง HTTP GET request

js
http.get("http://example.com", res => {
  let data = "";
  res.on("data", chunk => data += chunk);
  res.on("end", () => console.log(data));
});

กรณีใช้งานจริง

  • สร้าง web server ที่รับ request และส่ง response ได้เอง
  • ใช้สำหรับ proxy หรือ API gateway
  • ใช้สำหรับ monitor หรือ health check

อ้างอิง