บันทึกการหัดใช้ Node.js ด้วยใช้ framework Express
Server ที่เล็กที่สุดที่เรียกว่า serer ได้ก็คือ app สามารถ ฟัง (listen) ที่ port ที่เรากำหนด เมื่อมีการเรียกเข้ามาด้วย get request ก็ส่งข้อมูล Text กลับไป ซึ่งจะแสดงผลบน browser
ขั้นตอน
- สร้าง folder สำหรับ project
- เข้าไปที่ folder => cd newproject
- run npm init
- run npm install express
npm init
npm i express
- สร้างไฟล์ app.js
- edit ในไฟล์ app.js ด้วย
const express = require('express');
const app = express();
app.get("/",function(req,res){
res.send("Hello Yordja");
});
app.listen(process.env.PORT || 3000, function(req,res){ // ใส่ process.env.PORT ไว้เวลาไป run ที่server อื่นเช่น Heroku
console.log("App is runing on port 3000");
});
ใช้งาน ejs : เป็น Template engine สำหรับ render html มีการส่งตัวแปรข้ามไฟล์ได้ เตรียม template ไว้ให้เอาข้อมูลมาวางเป็น Layout
ติดตั้ง ejs ผ่านทาง npm
npm i ejs
ประกาศการใช้งาน ejs
สร้าง folder “views” เพื่อเก็บ template
ตัวอย่าง สร้าง template นามสกุล .ejs => “home.ejs”
<h1>Home from EJS Template</h1>
ในไฟล์ app.js เพิ่ม code เพื่อเรียกใช้งาน ejs
const ejs = require('ejs');
....
app.set('view engine','ejs');
....
app.get("/",function(req,res){
res.render("home"); // บอกว่าให้ render ไฟล์ไหน ไฟล์นี้จะอยู่ใน folder views
});
ทดลอง run “node app.js” และ เข้า browser

ส่งตัวแปร เข้าไปใน ejs
การแสดงค่าจะใช้ <%= ตัวแปร %> ตัวอย่าง
// ไฟล์ home.ejs //
<h1>Home from EJS Template</h1>
<p><%= startContent %></p>
// ไฟล์ app.js //
...
const homeStartingContent = "Home start content";
...
app.get("/",function(req,res){
res.render("home",{startContent: homeStartingContent}); // ส่งค่า ไปใส่ในตัวแปรปลายทางชื่อ startContent
});
