Express.js เบื้องต้น: สร้าง REST API แรก
Express Developer•20 ธันวาคม 2567•Express Basics
ExpressNode.jsREST APIBackendJavaScript
Express.js เป็น web framework ที่ได้รับความนิยมสูงสุดสำหรับ Node.js ที่ช่วยให้การสร้าง web applications และ APIs เป็นเรื่องง่าย
การติดตั้งและเริ่มต้น
# สร้างโปรเจ็คใหม่ npm init -y npm install express # สำหรับ development npm install -D nodemon
สร้าง Server พื้นฐาน
// app.js const express = require('express') const app = express() const PORT = process.env.PORT || 3000 // Middleware สำหรับ parsing JSON app.use(express.json()) app.use(express.urlencoded({ extended: true })) // Basic route app.get('/', (req, res) => { res.json({ message: 'Welcome to Express API!', timestamp: new Date().toISOString() }) }) // Start server app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`) })
REST API Routes
// routes/users.js const express = require('express') const router = express.Router() // Mock data let users = [ { id: 1, name: 'John Doe', email: 'john@example.com' }, { id: 2, name: 'Jane Smith', email: 'jane@example.com' } ] // GET /api/users - ดึงข้อมูล users ทั้งหมด router.get('/', (req, res) => { res.json({ success: true, data: users }) }) // GET /api/users/:id - ดึงข้อมูล user ตาม ID router.get('/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)) if (!user) { return res.status(404).json({ success: false, message: 'User not found' }) } res.json({ success: true, data: user }) }) // POST /api/users - สร้าง user ใหม่ router.post('/', (req, res) => { const { name, email } = req.body // Validation if (!name || !email) { return res.status(400).json({ success: false, message: 'Name and email are required' }) } const newUser = { id: users.length + 1, name, email } users.push(newUser) res.status(201).json({ success: true, data: newUser }) }) // PUT /api/users/:id - อัปเดต user router.put('/:id', (req, res) => { const userIndex = users.findIndex(u => u.id === parseInt(req.params.id)) if (userIndex === -1) { return res.status(404).json({ success: false, message: 'User not found' }) } users[userIndex] = { ...users[userIndex], ...req.body } res.json({ success: true, data: users[userIndex] }) }) // DELETE /api/users/:id - ลบ user router.delete('/:id', (req, res) => { const userIndex = users.findIndex(u => u.id === parseInt(req.params.id)) if (userIndex === -1) { return res.status(404).json({ success: false, message: 'User not found' }) } users.splice(userIndex, 1) res.json({ success: true, message: 'User deleted successfully' }) }) module.exports = router
การใช้งาน Router
// app.js const express = require('express') const userRoutes = require('./routes/users') const app = express() // Middleware app.use(express.json()) // Routes app.use('/api/users', userRoutes) // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack) res.status(500).json({ success: false, message: 'Something went wrong!' }) }) // 404 handler app.use('*', (req, res) => { res.status(404).json({ success: false, message: 'Route not found' }) }) const PORT = process.env.PORT || 3000 app.listen(PORT, () => { console.log(`Server running on port ${PORT}`) })
Package.json Scripts
{ "scripts": { "start": "node app.js", "dev": "nodemon app.js", "test": "jest" } }
การทดสอบ API
# GET all users curl http://localhost:3000/api/users # GET user by ID curl http://localhost:3000/api/users/1 # POST new user curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"name":"Bob Johnson","email":"bob@example.com"}' # PUT update user curl -X PUT http://localhost:3000/api/users/1 \ -H "Content-Type: application/json" \ -d '{"name":"John Updated"}' # DELETE user curl -X DELETE http://localhost:3000/api/users/1
Best Practices
- ใช้ Environment Variables - เก็บค่า config ที่สำคัญ
- Error Handling - จัดการ errors อย่างเหมาะสม
- Validation - validate input data เสมอ
- Status Codes - ใช้ HTTP status codes ที่ถูกต้อง
- Consistent Response Format - รูปแบบ response ที่สม่ำเสมอ
สรุป
Express.js ช่วยให้การสร้าง REST API เป็นเรื่องง่ายด้วย routing system ที่ยืดหยุ่นและ middleware pattern ที่ทรงพลัง เหมาะสำหรับการเริ่มต้นสร้าง backend applications