(This document is written in Thai language)
ขั้นตอนแรกคือการเพิ่ม Node.js , Express Framework และ Morgan
ในส่วนของ Node.js ต้องทำการโหลดจากหน้าเว็บมาติดตั้ง
ส่วน Express และ Morgan จะติดตั้งโดยการพิมพ์ Command Line ลงใน Terminal และต้องลงใน Directory ที่สร้างเว็บ
Express : npm install express
Morgan : npm install morgan
เมื่อทำการติดตั้งจะได้ ไฟล์ดังนี้
ใส่ const ที่จำเป็นในการรัน web server เช่น Express ซึ่งเป็น Framework , morgan ใช้สำหรับ log Request ใน Server
contentRouter เพื่อรับ export จากไฟล์ index.js ที่อยู่ใน content
เพื่อให้สามารถปรับ port ตามที่ Web Hosting (Render) สุ่มมาให้ ให้ใส่คำสั่ง port ดังนี้
port = process.env.port || 3030;
เข้าถึงไฟล์ที่อยู่ใน Folder public ซึ่งในที่นี้คือ stylesheet (style.css)
app.use(express.static(‘public’)
ตั้งค่า morgan ให้ รัน log จาก Request
app.use(morgan(“common”,{immediate:true}));
รับ contentRouter ที่กำหนดใว้ใน const
app.use(‘/content’,contentRouter)
redirect เข้าไปที่ content
app.get('/',(req, res)=> res.redirect('/content'));
log ว่า server รันที่ port ไหน ใช้สำหรับตรวจสอบใน Local ว่า Website ใช้ได้ไหม
app.listen(port,() => console.log(`Server Running at port http://localhost:${port}`));
ไฟล์นี้เปรียบเสมือน Router ระหว่าง content กับ main directory ซึ่งจะทำการรับค่าจาก controller และส่งไปหา index.js ใน main
const router = express.Router();
ใช้เป็น middleware สำหรับ routing system
รับค่าจาก model และ view และรัน function listAction เพื่อส่งไปหา index.js
ซึ่งเป็น function แบบ async await โดยให้ await รอข้อมูลผ่าน
const data = await getAll();
เมื่อได้แล้วจะนำมา render เป็นเว็ปและรัน variable จาก Data ผ่าน body
body (const body = render(data);)
และตอบสนองโดยการส่ง body ออกไป
ไฟล์ตัวนี้ไว้เก็บ data เพื่อใช้ในการแสดงข้อมูลโดยเก็บข้อมูลแบบ array และส่งข้อมูลไปหา controller.js ผ่าน function getAll() และทำให้วงจร Async สมบูรณ์
ไฟล์ที่ใช้สำหรับ Render หน้าเว็บ โดยมี index.html เป็น template เพื่อให้ทำหน้าเว็บสะดวกขึ้น
โดยหน้าเว็บมีต้นแบบมาจาก https://help.abstract.com/hc/en-us เพื่อฝึกทำหน้าเว็บ และดัดแปลงเพื่อให้ทำการแสดงข้อมูลจาก Model ขึ้นหน้าเว็บได้
และ .join(‘’) ใช้เพื่อลบ ‘,’ ที่แสดงผลระหว่าง array ออก
ใช้สำหรับตกแต่งหน้าเว็บให้เป็นไปตามต้องการ ซึ่งมีการทำให้เป็น Responsive และจัดให้หน้าเว็บอยู่ในความเหมาะสม