เนื้อหาดังต่อไปนี้เป็นเนื้อหาเมื่อปี 2023 ถูกปรับปรุงเรียบเรียงใหม่ 2026 ขอให้สนุกกับการเริ่มต้นกับโลก Programming อย่างภาษาง่าย ๆ ด้วย JavaScript กันเน่อ :)
🚀 การสร้าง API โดยใช้ JavaScript Node.js Express
คู่มือการพัฒนา RESTful API แบบครบวงจรด้วย Node.js, Express, Sequelize และ MySQL
📖 คำนำ
เอกสารฉบับนี้เป็นการพัฒนา web service หรือ RESTful API โดยใช้ภาษา JavaScript Node.js ร่วมกับเฟรมเวิร์กและไลบรารี่ต่าง ๆ ได้แก่:
- 🌐 Express HTTP Framework - สำหรับสร้าง web server
- 🗄️ Sequelize - ORM สำหรับจัดการฐานข้อมูล
- 💾 MySQL - ฐานข้อมูลเชิงสัมพันธ์
- 🔧 POSTMAN - สำหรับทดสอบ API
Module 1: 📡 Basic API
เรียนรู้พื้นฐานการสร้าง API ด้วย Node.js และ Express
Section 1-1 - 🎯 Intro
📝 เริ่มต้นสร้าง Server ด้วย HTTP Library
สร้างไฟล์ server.js สำหรับสร้าง server พื้นฐานโดยใช้ HTTP library ของ Node.js
ไฟล์: server.js
const http = require('http')
const HOSTNAME = '127.0.0.1';
const PORT = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World \n')
})
server.listen(PORT, HOSTNAME, () => {
console.log(`Server running at http://${HOSTNAME}:${PORT}`)
})
⚠️ หมายเหตุ: ในโค้ดตัวอย่างมีการใช้ตัวแปร
hostnameและportแบบตัวพิมพ์เล็ก ซึ่งควรเป็นHOSTNAMEและPORTตามที่ประกาศไว้
🔧 ติดตั้ง Nodemon
Nodemon เป็นเครื่องมือที่ช่วยให้ server รีสตาร์ทอัตโนมัติเมื่อมีการแก้ไขไฟล์
📦 ติดตั้งสำหรับ Development Dependencies
npm install -D nodemon
หรือ
npm install --save-dev nodemon
🌐 ติดตั้งแบบ Global
npm install -g nodemon
▶️ วิธีใช้งาน
nodemon index.js
💡 เคล็ดลับ: แทนที่
index.jsด้วยชื่อไฟล์แอปพลิเคชันของเราดูครับ
Section 1-2 - 🛣️ สร้าง Route ด้วย Express
📦 ติดตั้ง Express Framework
npm install express --save
📄 สร้างไฟล์ app.js
สร้างไฟล์ app.js และเพิ่มโค้ดสำหรับ import Express และสร้าง route พื้นฐาน
ไฟล์: app.js
const express = require('express');
const app = express();
app.use(express.json())
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello Express!');
});
app.listen(PORT, () => {
console.log(`Listening at http://localhost:${PORT}`);
});
🔍 อธิบายโค้ด:
-
express()- สร้าง Express application instance -
app.use(express.json())- เปิดใช้งาน JSON parser middleware -
app.get('/')- สร้าง GET route ที่ path/ -
app.listen()- เริ่มต้น server ที่ port ที่กำหนด
▶️ รันแอปเพื่อทดสอบ
nodemon app.js
เปิดเบราว์เซอร์ไปที่ http://localhost:3000 เพื่อดูผลลัพธ์
Section 1-3 - 💡 ตัวอย่างการสร้าง API
📄 สร้างไฟล์ app-demo.js
ตัวอย่างการสร้าง API แบบง่าย ๆ พร้อมการกำหนด PORT จาก environment variable
ไฟล์: app-demo.js
const express = require('express')
const app = express();
const PORT = process.env.PORT || 5000
app.get('/', (req, res) => {
res.send("Hello! Node.js")
})
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
🔍 จุดเด่นของโค้ด:
- ✅ ใช้
process.env.PORTเพื่อรองรับการ deploy บน cloud platforms - ✅ มีค่า default เป็น
5000หากไม่มีการกำหนด PORT - ✅ โครงสร้างโค้ดเรียบง่ายและเข้าใจง่าย
▶️ รันแอปเพื่อทดสอบ
nodemon app-demo.js
หรือกำหนด PORT ก่อนรัน:
PORT=3000 nodemon app-demo.js
Section 1-4 - ⚙️ การสร้าง Scripts
📝 สร้าง Scripts ใน package.json
สร้าง script เพื่อรันแอปพลิเคชันได้ง่ายขึ้น โดยเราสามารถแก้ไขได้ที่ package.json ในส่วน scripts
ตัวอย่างการตั้งค่า:
"scripts": {
"dev": "nodemon ./server.js"
}
📸 ตัวอย่าง package.json
ไฟล์: package.json
{
"name": "server",
"version": "1.0.0",
"description": "example javascript or node.js application that use express http framework",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon ./server.js"
},
"keywords": [],
"author": "billowdev",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"mysql2": "^3.2.0",
"sequelize": "^6.30.0"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
▶️ วิธีใช้งาน Script
หลังจากเพิ่ม script แล้ว ลองรันแอปด้วยคำสั่งนี้ดูครับ
npm run dev
💡 ประโยชน์: ไม่ต้องพิมพ์
nodemon ./server.jsทุกครั้ง แค่พิมพ์npm run devก็พอ
Section 1-5 - 🔄 RESTful API
📄 สร้างไฟล์ db.json สำหรับจำลองข้อมูล
สร้างไฟล์ db.json เพื่อใช้เป็นฐานข้อมูลจำลองสำหรับทดสอบ API
ไฟล์: db.json
[
{
"id": 1,
"username": "user1",
"name": "Alice"
},
{
"id": 2,
"username": "user2",
"name": "Lac"
},
{
"id": 3,
"username": "user3",
"name": "Billo"
}
]
📥 Import ข้อมูลจาก db.json
const users = require('./db.json')
🛣️ สร้าง Route สำหรับดึงข้อมูล Users
app.get('/users', (req, res) => {
res.json(users)
})
📝 ตัวอย่างโค้ดเต็มใน app-demo.js
ไฟล์: app-demo.js
const express = require('express')
const app = express();
const PORT = process.env.PORT || 5000
const users = require('./db.json')
app.get('/', (req, res) => {
res.send("Hello! Node.js")
})
app.get('/users', (req, res) => {
res.json(users)
})
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
🧪 ทดสอบ API
- รันแอปพลิเคชัน:
nodemon app-demo.js
- ทดสอบด้วย Browser หรือ Postman:
-
GET http://localhost:5000/- ดูข้อความต้อนรับ -
GET http://localhost:5000/users- ดูรายการ users ทั้งหมด
-
Section 1-6 - 📥 Method GET and API Params
🎯 สร้าง Route สำหรับดึงข้อมูล User ตาม ID
สร้าง API route ที่มี endpoint เป็น /users/:id เพื่อดึงข้อมูล user เฉพาะคนจาก users array
📌 Route Parameters
app.get('/users/:id', (req, res) => {
res.json(users.find(el => el.id === Number(req.params.id)))
})
🔍 อธิบายโค้ด:
-
:id- Route parameter ที่จะรับค่า id จาก URL -
req.params.id- ดึงค่า id จาก URL parameter -
Number()- แปลง string เป็น number -
find()- ค้นหา user ที่มี id ตรงกับที่ระบุ
📝 ตัวอย่างโค้ดเต็มใน api-demo.js
ไฟล์: api-demo.js
const express = require('express')
const app = express();
const PORT = process.env.PORT || 5000
const users = require('./db.json')
app.get('/', (req, res) => {
res.send("Hello! Node.js")
})
app.get('/users', (req, res) => {
res.status(200).json(users)
})
app.get('/users/:id', (req, res) => {
res.json(users.find(el => el.id === Number(req.params.id)))
})
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
🧪 ทดสอบ API
-
GET http://localhost:5000/users/1- ดึงข้อมูล user ที่มี id = 1 -
GET http://localhost:5000/users/2- ดึงข้อมูล user ที่มี id = 2 -
GET http://localhost:5000/users/3- ดึงข้อมูล user ที่มี id = 3
⚠️ หมายเหตุ: หากไม่พบ user ที่ระบุ จะได้ค่า
undefinedแนะนำให้เพิ่มการตรวจสอบและส่ง error response กันนะครับ
Section 1-7 - 📤 Using JSON and Method POST
📦 ติดตั้ง body-parser (Optional)
💡 หมายเหตุ: ใน Express 4.16+ เราสามารถใช้
express.json()แทนbody-parserได้โดยไม่ต้องติดตั้งเพิ่มนะครับ
npm install body-parser --save
🔧 วิธีใช้งาน JSON Parser
วิธีที่ 1: ใช้ body-parser
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
วิธีที่ 2: ใช้ Express (แนะนำ) ⭐
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
✅ แนะนำ: ใช้วิธีที่ 2 กันนะครับ เพราะไม่ต้องติดตั้ง package เพิ่ม และ Express รองรับอยู่แล้ว
➕ สร้าง User โดยใช้ Method POST
app.post('/users', (req, res) => {
// push ข้อมูลจาก body ไปใน users array
users.push(req.body)
// ดึงเฉพาะข้อมูล username เก็บไว้ในตัวแปร username
let username = req.body.username
// ส่ง response กลับไปให้ผู้ใช้ API
res.json(`Add user: '${username}' was successfully.`)
})
🔍 อธิบายโค้ด:
-
app.post()- สร้าง POST route -
req.body- ข้อมูลที่ส่งมาจาก client (JSON) -
users.push()- เพิ่มข้อมูลใหม่เข้าไปใน array -
res.json()- ส่ง response กลับเป็น JSON
📝 ตัวอย่างโค้ดเต็มใน api-demo.js
ไฟล์: api-demo.js
const express = require('express')
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 5000
const users = require('./db.json')
app.get('/', (req, res) => {
res.send("Hello! Node.js")
})
app.get('/users', (req, res) => {
res.status(200).json(users)
})
app.get('/users/:id', (req, res) => {
res.json(users.find(el => el.id === Number(req.params.id)))
})
// สร้าง users
app.post('/users', (req, res) => {
// push ข้อมูลจาก body ไปใน users array
users.push(req.body)
// ดึงเฉพาะข้อมูล username เก็บไว้ในตัวแปร username
let username = req.body.username
// ส่ง response กลับไปให้ผู้ใช้ API
res.json(`Add user: '${username}' was successfully.`)
})
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
🧪 ทดสอบ API ด้วย Postman
-
Method:
POST -
URL:
http://localhost:5000/users - Headers:
Content-Type: application/json
- Body (raw JSON):
{
"id": 4,
"username": "user4",
"name": "John"
}
✅ Response ที่คาดหวัง:
"Add user: 'user4' was successfully."
Section 1-8 - ✏️ Method PUT
🔄 อัปเดตข้อมูล User โดยใช้ Method PUT
Method PUT ใช้สำหรับอัปเดตข้อมูลที่มีอยู่แล้ว
📌 Route สำหรับอัปเดต User
app.put('/users/:id', (req, res) => {
// ค้นหา index ของ user ด้วย id ที่รับมาจาก params
const userIndex = users.findIndex(user => user.id === Number(req.params.id))
// ตรวจสอบว่าพบ user หรือไม่
if (userIndex !== -1) {
// อัปเดตข้อมูล user
users[userIndex] = { ...users[userIndex], ...req.body }
res.json(`Update user id: '${users[userIndex].id}' was successfully.`)
} else {
res.status(404).json({ message: 'User not found' })
}
})
🔍 อธิบายโค้ด:
-
findIndex()- ค้นหา index ของ user ใน array -
...users[userIndex]- spread operator เพื่อคงข้อมูลเดิม -
...req.body- spread operator เพื่ออัปเดตข้อมูลใหม่ - ตรวจสอบ
userIndex !== -1เพื่อยืนยันว่าพบ user
📝 ตัวอย่างโค้ดเต็มใน api-demo.js
ไฟล์: api-demo.js
const express = require('express')
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 5000
const users = require('./db.json')
app.get('/', (req, res) => {
res.send("Hello! Node.js")
})
app.get('/users', (req, res) => {
res.status(200).json(users)
})
app.get('/users/:id', (req, res) => {
res.json(users.find(el => el.id === Number(req.params.id)))
})
// สร้าง users
app.post('/users', (req, res) => {
users.push(req.body)
let username = req.body.username
res.json(`Add user: '${username}' was successfully.`)
})
// อัปเดต user
app.put('/users/:id', (req, res) => {
// ค้นหา user ด้วย id ที่รับมาจาก params
const userIndex = users.findIndex(user => user.id === Number(req.params.id))
if (userIndex !== -1) {
// อัปเดตข้อมูล
users[userIndex] = { ...users[userIndex], ...req.body }
res.json(`Update user id: '${users[userIndex].id}' was successfully.`)
} else {
res.status(404).json({ message: 'User not found' })
}
})
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
🧪 ทดสอบ API ด้วย Postman
-
Method:
PUT -
URL:
http://localhost:5000/users/1 - Headers:
Content-Type: application/json
- Body (raw JSON):
{
"username": "user1_updated",
"name": "Alice Updated"
}
✅ Response ที่คาดหวัง:
"Update user id: '1' was successfully."
Section 1-9 - 🗑️ Method DELETE
🗑️ ลบข้อมูล User โดยใช้ Method DELETE
Method DELETE ใช้สำหรับลบข้อมูลที่มีอยู่แล้ว
📌 Route สำหรับลบ User
app.delete('/users/:id', (req, res) => {
const userIndex = users.findIndex(user => user.id === Number(req.params.id))
if (userIndex !== -1) {
const deletedUser = users[userIndex]
// ลบ user ออกจาก array
users.splice(userIndex, 1)
res.json(`Delete user '${deletedUser.username}' was successfully.`)
} else {
res.status(404).json({ message: 'User not found' })
}
})
🔍 อธิบายโค้ด:
-
findIndex()- ค้นหา index ของ user ใน array -
splice(userIndex, 1)- ลบ element 1 ตัวที่ตำแหน่ง userIndex - ตรวจสอบ
userIndex !== -1เพื่อยืนยันว่าพบ user
📝 ตัวอย่างโค้ดเต็มใน api-demo.js (CRUD Complete)
ไฟล์: api-demo.js
const express = require('express')
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 5000
const users = require('./db.json')
// Home route
app.get('/', (req, res) => {
res.send("Hello! Node.js")
})
// Get all users
app.get('/users', (req, res) => {
res.status(200).json(users)
})
// Get user by id
app.get('/users/:id', (req, res) => {
const user = users.find(el => el.id === Number(req.params.id))
if (user) {
res.json(user)
} else {
res.status(404).json({ message: 'User not found' })
}
})
// Create user
app.post('/users', (req, res) => {
users.push(req.body)
let username = req.body.username
res.status(201).json(`Add user: '${username}' was successfully.`)
})
// Update user
app.put('/users/:id', (req, res) => {
const userIndex = users.findIndex(user => user.id === Number(req.params.id))
if (userIndex !== -1) {
users[userIndex] = { ...users[userIndex], ...req.body }
res.json(`Update user id: '${users[userIndex].id}' was successfully.`)
} else {
res.status(404).json({ message: 'User not found' })
}
})
// Delete user
app.delete('/users/:id', (req, res) => {
const userIndex = users.findIndex(user => user.id === Number(req.params.id))
if (userIndex !== -1) {
const deletedUser = users[userIndex]
users.splice(userIndex, 1)
res.json(`Delete user '${deletedUser.username}' was successfully.`)
} else {
res.status(404).json({ message: 'User not found' })
}
})
app.listen(PORT, () => {
console.log(`SERVER ON PORT ${PORT}`)
})
🧪 ทดสอบ API ด้วย Postman
-
Method:
DELETE -
URL:
http://localhost:5000/users/1
✅ Response ที่คาดหวัง:
"Delete user 'user1' was successfully."
🎉 สรุป Module 1
เราได้เรียนรู้การสร้าง RESTful API แบบพื้นฐานครบทั้ง CRUD Operations กันแล้ว:
| Method | Endpoint | Description |
|---|---|---|
GET |
/users |
ดึงข้อมูล users ทั้งหมด |
GET |
/users/:id |
ดึงข้อมูล user ตาม id |
POST |
/users |
สร้าง user ใหม่ |
PUT |
/users/:id |
อัปเดตข้อมูล user |
DELETE |
/users/:id |
ลบ user |
Reference
akkaraponph
/
basic-nodejs-express-sequelize-mysql
สร้าง API โดยใช้ JavaScript Node.js Express
หมายเหตุ Tutorial นี้ได้จัดทำขึ้นเมื่อ (April 4th, 2023) และได้รับการปรับปรุงเมื่อ (January 8th, 2026)
🚀 การสร้าง API โดยใช้ JavaScript Node.js Express
คู่มือการพัฒนา RESTful API แบบครบวงจรด้วย Node.js, Express, Sequelize และ MySQL
📖 คำนำ
เอกสารฉบับนี้เป็นการพัฒนา web service หรือ RESTful API โดยใช้ภาษา JavaScript Node.js ร่วมกับเฟรมเวิร์กและไลบรารี่ต่าง ๆ ได้แก่:
- 🌐 Express HTTP Framework - สำหรับสร้าง web server
- 🗄️ Sequelize - ORM สำหรับจัดการฐานข้อมูล
- 💾 MySQL - ฐานข้อมูลเชิงสัมพันธ์
- 🔧 POSTMAN - สำหรับทดสอบ API
📚 สารบัญ
- Section 1-1 - 🎯 Intro
- Section 1-2 - 🛣️ สร้าง Route ด้วย Express
- Section 1-3 - 💡 ตัวอย่างการสร้าง API
- Section 1-4 - ⚙️ การสร้าง Scripts
- Section 1-5 - 🔄 RESTful API
- Section 1-6 - 📥 Method GET and API Params
- Section 1-7 - 📤 Using JSON and Method POST
- Section 1-8 - ✏️ Method PUT
- Section 1-9 - 🗑️ Method DELETE


Top comments (0)