ข้ามไปยังเนื้อหา

การสร้าง HTTP Server

http.createServer(callback) คืนค่า Server instance โดย callback — เรียกว่า request listener — จะถูกเรียกทุกครั้งที่มี HTTP request เข้ามา โดยรับ argument สองตัวคือ:

  • req — object IncomingMessage ที่อธิบาย request (method, URL, headers, body stream)
  • res — object ServerResponse ที่ใช้เขียน response

เรียก server.listen(port, callback) เพื่อเริ่มรับ connection โดย callback จะทำงานเมื่อ server พร้อมแล้ว

HTTP response ทุกอันมี status code และชุด headers ใช้ res.writeHead(statusCode, headersObject) เพื่อกำหนดทั้งสองอย่างพร้อมกันก่อนที่จะเขียน body ใด ๆ

status codes ที่ใช้บ่อย:

Codeความหมาย
200OK
201Created
400Bad Request
404Not Found
500Internal Server Error

res.end(data) เขียน chunk สุดท้ายของ response body และบอก Node.js ว่า response เสร็จสมบูรณ์แล้ว ทุก request handler ต้อง เรียก res.end() (หรือ res.destroy()) — ถ้าลืม client จะรอไปตลอดและ connection จะ timeout

คุณยังสามารถใช้ res.write(data) เพื่อส่งข้อมูลเป็น chunk ก่อนที่จะเรียก res.end() ได้

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

เปิดใน StackBlitz แล้วเข้า http://localhost:3000 ใน preview tab เพื่อดู HTML response ที่ render ออกมาพร้อม headers ที่ถูกต้อง

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

จุดประสงค์ของ res.end() ใน Node.js HTTP server คืออะไร?
method ใดที่กำหนดทั้ง status code และ response headers ในครั้งเดียว?
จะเกิดอะไรขึ้นถ้าลืมเรียก res.end() ใน request handler?