ใน workshop นี้ให้ทุกคนติดตั้ง Xampp, vscode และ nodeJs
โดยที่ต้องติดตั้ง package npm ดังนี้
โค้ด: เลือกทั้งหมด
npm init -y
npm install express
npm install ejs
npm install mysql
npm install express-validator
จากนั้นให้เปิด Vscode ขึ้นมา และติดตั้ง package npm ให้เรียบร้อย สร้าง folder views และไฟล์ app.js ดังภาพ
โดย folder views เราจะใช้เก็บ templates หรือ layout ส่วนไฟล์ app.js เป็นตัว application nodejs ของเรา
เขียนโค้ดที่ไฟล์ app.js ดังนี้
โค้ด: เลือกทั้งหมด
const express = require('express')
const app = express()
const mysql = require('mysql')
app.set('view engine','ejs')
var conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test'
})
conn.connect(function (error)
{
if(error){
console.log(error)
} else{
console.log("MySQL Connected!")
}
})
app.get("/", (request,response) =>{
var sql = "SELECT test.* from person "
conn.query(sql, function(error,results,fiels){
if (error){
console.log(error)
} else{
response.render("home",
{
resultsPerson : results
})
}
})
})
app.listen(3000, () => console.log("Server started on port : 3000"))
// results คือค่าที่หน้าจะโยนออกไปแสดงผลที่ layout
โค้ด: เลือกทั้งหมด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NodeJs</title>
</head>
<body>
<h2>Hello</h2>
</body>
</html>
โค้ด: เลือกทั้งหมด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NodeJs</title>
</head>
<body>
<table width = "800" border = "1">
<thead>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
</thead>
<tbody>
<% if (resultsPerson.length > 0) { %>
<% resultsPerson.forEach (function(recordPerson) { %>
<tr>
<td>
<%= recordPerson.id %>
</td>
<td>
<%= recordPerson.firstname %>
</td>
<td>
<%= recordPerson.lastname %>
</td>
</tr>
<% }) %>
<% } else { %>
<tr>
<td colspan = "100%">- ไม่มีข้อมูล -</td>
</tr>
<% } %>
</tbody>
</table>
</body>
</html>
ไปที่หน้า browser ที่ช่อง URL ให้พิมพ์ว่า localhost:3000 จากนั้นจะปรากฏหน้าต่างของ website ของเราขึ้นซึ่งยังไม่มีข้อมูล
ถ้าหากอยากให้มีการแสดงข้อมูลให้เราไปทำการ insert ข้อมูลจาก MySQL ดังรูปภาพนี้
จากนั้นให้เปิดหน้า website ขึ้นมาอีกครั้งเพื่อทำการแสดงผล
สรุปจากบทความนี้ เป็นความรู้จาก mini project ที่ได้รับ ซึ่งอยากจะแชร์ความรู้ออกมาเป็นบทความหาก เพื่อมีใครที่สนใจอยากรู้แนวทางเบื้องต้นในการใช้ NodeJs เราก็สามารถนำนี่ไปประยุกต์ใช้งาน ได้ และสามารถประยุกต์ใช้งานกับ ได้กับ form คือการรับข้อมูลมาจาก form จากฝั่งของ client ที่เข้ามาใช้งาน สามารถอ่านได้จาก บทความ
การรับข้อมูลจาก form และบันทึกลงใน MySQL ด้วย , NodeJS ซึ่งทั้ง 2 บทความจะเกี่ยวพันธ์กันเราสามารถเอาความรู้จากบทนี้และ บท ความ การรับข้อมูลจาก form และบันทึกลงใน MySQL ด้วย NodeJS มาใช้งานร่วมกันได้