A PHP Error was encountered

Severity: Notice

Message: Only variable references should be returned by reference

Filename: core/Common.php

Line Number: 257

สอน Node.js ตอนที่ 2 เขียนแอพพลิเคชั่นแรกด้วย Node.js | Share

สอน Node.js ตอนที่ 2 เขียนแอพพลิเคชั่นแรกด้วย Node.js

สอน Node.js ตอนที่ 2 เขียนแอพพลิเคชั่นแรกด้วย Node.js

ติดตั้งเครื่องมือสำหรับเขียนแอพพลิเคชั่นด้วย Node.js สร้าง Server สำหรับรับ http request จาก Browser และส่งข้อมูลกลับ

Nov 30, 2017

แก้ไขล่าสุด มีผู้อ่าน 14,344  |  NODE.JS

เมื่อเราติดตั้ง Node.js เสร็จเรียบร้อย มาลองเขียนแอพพลิเคชั่นแรกด้วย Node.js กันครับ ก่อนเขียนก็หาเครื่องมือดีๆ ซักตัวสำหรับเขียน Node.js แนะนำตัวที่ใช้อยู่คือ Visual Studio Code เนื่องจากกินทรัพยากรเครื่องน้อย เปิดเร็ว และมี Add On ให้ติดตั้งเพิ่มเติมเยอะมาก ช่วยอำนวยความสะดวกในการเขียนโปรแกรมได้เป็นอย่างดี https://code.visualstudio.com

 

แอพพลิเคชั่นแรก เราจะลองสร้าง Server เมื่อเรียกมาที่ http://127.0.0.1:8081 จะส่งค่ากลับไปเป็น "Hello World"

 

สร้างโฟลเดอร์สำหรับพัฒนา Node.js ในเครื่องซักที่หนึ่ง ต่อมาสร้างไฟล์ main.js เขียนโค้ดคำสั่งตามด้านล่าง

var http = require("http");

http.createServer(function(request, response) {
    // Send the HTTP header 
    // HTTP Status: 200 : OK
    // Content Type: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});
   
    // Send the response body as "Hello World"
    response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

 

อธิบายโค้ด

var http = require("http");

Import โมดูล http ของ  Node.js มาใช้งาน และเก็บมันไว้ในตัวแปร http | http เป็น Build In โมดูลของ Node.js ใช้สำหรับส่งข้อมูลผ่าน Hyper Text Transfer Protocol (HTTP)

 

http.createServer(function(request, response) {
    // Send the HTTP header 
    // HTTP Status: 200 : OK
    // Content Type: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});
   
    // Send the response body as "Hello World"
    response.end('Hello World\n');
}).listen(8081);

ใช้ตัวแปร http เรียกฟังก์ชั่น http.createServer(...) ในการสร้าง Server เพื่อรอรับ Request และส่งกลับค่า Response ให้กับคนที่เรียกใช้เข้ามาที่ port 8081 จากโค้ดเราจะส่งข้อมูลกลับไปเป็นชนิด text/plain เป็นข้อความ "Hello World"

 


สั่งทำงานได้โดยใช้คำสั่ง node ตามด้วยไฟล์ main.js

$ node main.js

 

ทดสอบเปิด Browser แล้ว พิมพ์ http://127.0.0.1:8081 จะได้ผลตามรูปด้านล่าง

 

 


แบ่งปัน

ชอบ +1

บันทึก

ฝากคำถาม คำแนะนำ ได้ที่

Facebook : Share.OlanLab.Com
LINE ID : @olanlab
อีเมล์ : olan@olanlab.com
Share คลังความรู้ด้านเทคโนโลยี สารสนเทศ นวัตกรรมคอมพิวเตอร์ สอนเขียนโปรแกรม Php Java Html CSS Javascript C C++ Objective-C และอื่นๆ บนระบบปฏิบัติการ Window Linux Unix CentOS IOS Android
โดยผู้เขียนที่มีความเชี่ยวชาญเฉพาะ ให้บริการพื้นที่สำหรับนักเขียนที่ต้องการแบ่งปันความรู้ พร้อมให้คำปรึกษาแก่ผู้ที่สนใจ โดยไม่เสียค่าใช้จ่าย