การสร้าง HTTP Server
http.createServer
หัวข้อที่มีชื่อว่า “http.createServer”http.createServer(callback) คืนค่า Server instance โดย callback — เรียกว่า request listener — จะถูกเรียกทุกครั้งที่มี HTTP request เข้ามา โดยรับ argument สองตัวคือ:
req— objectIncomingMessageที่อธิบาย request (method, URL, headers, body stream)res— objectServerResponseที่ใช้เขียน response
เรียก server.listen(port, callback) เพื่อเริ่มรับ connection โดย callback จะทำงานเมื่อ server พร้อมแล้ว
Status codes และ Headers
หัวข้อที่มีชื่อว่า “Status codes และ Headers”HTTP response ทุกอันมี status code และชุด headers ใช้ res.writeHead(statusCode, headersObject) เพื่อกำหนดทั้งสองอย่างพร้อมกันก่อนที่จะเขียน body ใด ๆ
status codes ที่ใช้บ่อย:
| Code | ความหมาย |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 404 | Not Found |
| 500 | Internal Server Error |
res.end — ส่ง response body
หัวข้อที่มีชื่อว่า “res.end — ส่ง response body”res.end(data) เขียน chunk สุดท้ายของ response body และบอก Node.js ว่า response เสร็จสมบูรณ์แล้ว ทุก request handler ต้อง เรียก res.end() (หรือ res.destroy()) — ถ้าลืม client จะรอไปตลอดและ connection จะ timeout
คุณยังสามารถใช้ res.write(data) เพื่อส่งข้อมูลเป็น chunk ก่อนที่จะเรียก res.end() ได้
Server ที่สมบูรณ์พร้อม status codes และ headers
หัวข้อที่มีชื่อว่า “Server ที่สมบูรณ์พร้อม status codes และ headers”Needs the Node.js runtime — open in StackBlitz to run.
เปิดใน StackBlitz แล้วเข้า http://localhost:3000 ใน preview tab เพื่อดู HTML response ที่ render ออกมาพร้อม headers ที่ถูกต้อง
การตอบกลับด้วย status codes ต่าง ๆ
หัวข้อที่มีชื่อว่า “การตอบกลับด้วย status codes ต่าง ๆ”Needs the Node.js runtime — open in StackBlitz to run.