Node.js การสร้าง Server

โดยทั่วไปเราจะสร้าง Server ขึ้นมาตัวหนึ่งเราจะใช้ Tool ต่างๆ เช่น xampp, Appserve เป็นต้น Node.js นั้นสามารถสร้าง Server ได้ตัวของมันเอง โดยเราไม่ต้องใช้ Tool ที่กล่าวมาเลย

สร้าง Server

ให้สร้าง Folder สำหรับเก็บไฟล์ขึ้นมาตัวหนึ่ง จากนั้นเขียนไฟล์ server.js ขึ้นมา

var http = require('http');http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
}).listen(8081, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8081/');

จากนั้นรันคำสั่งใน cmd

node server.js
รัน server ด้วยคำสั่ง node

ให้เราลองเปิด Browser แล้วพิมพ์ address กับ Pport ที่เรากำหนดไว้

หน้าตาของ address ที่เรากำหนดไว้

อธิบาย

http : เราเรียกใช้ module http ขึ้นมา โดยเจ้าตัว http นี้ เป็นตัวคอยจัดการ Server ต่างๆ

createServer : เป็นคำสั่งการสร้าง Server ของ Node.js โดย function จะมี request และ response

res.writeHead : กำหนด Content Type

res.end : เป็นคำสั่งที่จะถูกใช้งานต่อเมื่อ response สิ้นสุดแล้ว

listen : เป็นกคำสั่งกำหนด port และ address ของ Server ของเรา

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade