Express: ทำ API หลังบ้าน
ใช้ใน Challenge Day 3 · ส่วน E ของ PERN Stack
API คือประตูที่หน้าเว็บใช้คุยกับหลังบ้าน Express คือ framework บน Node.js ที่ทำให้เขียน API ได้ในไม่กี่บรรทัด: บอกว่า URL ไหน method ไหน ให้ทำอะไร
At a glance
| Method + URL | ทำอะไร |
|---|---|
GET /api/products | ดูสินค้าทั้งหมด |
GET /api/products/:id | ดูสินค้า 1 ชิ้น |
POST /api/orders | สร้างออเดอร์ใหม่ |
PATCH /api/orders/:id | เปลี่ยนสถานะออเดอร์ |
DELETE /api/products/:id | ลบสินค้า |
Installation
สร้างโปรเจกต์ Node.js
mkdir server && cd server npm init -yติดตั้ง package
npm install express pg cors dotenv npm install -D nodemonPackage ทำอะไร expressเว็บเซิร์ฟเวอร์และ routing pgตัวเชื่อม Node.js กับ PostgreSQL corsอนุญาตให้หน้าเว็บ (localhost:3000) เรียก API ได้ dotenvอ่านค่าจากไฟล์ .envnodemonเซฟแล้วรีสตาร์ตเซิร์ฟเวอร์เอง ตั้งค่า package.json
เพิ่ม
"type": "module"และ script สำหรับรัน{ "type": "module", "scripts": { "dev": "nodemon index.js", "start": "node index.js" } }ใส่ connection string
เอา URI จาก PostgreSQL › Installation ใส่ในไฟล์
.envและใส่.envใน.gitignoreDATABASE_URL=postgresql://postgres.xxxx:YOUR-PASSWORD@aws-0-ap-southeast-1.pooler.supabase.com:5432/postgres PORT=4000
Structure
server/
├── .env ← DATABASE_URL (ห้าม push)
├── .gitignore ← node_modules/ และ .env
├── package.json
├── db.js ← เชื่อมฐานข้อมูล
└── index.js ← เซิร์ฟเวอร์และ route// db.js
import pg from "pg";
import "dotenv/config";
export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });เขียน route
รูปแบบของทุก route: app.method(path, handler) handler ได้ req (สิ่งที่ส่งมา) และ res (ใช้ตอบกลับ)
// index.js
import express from "express";
import cors from "cors";
import { pool } from "./db.js";
const app = express();
app.use(cors());
app.use(express.json()); // อ่าน JSON จาก request body
// GET /api/products → สินค้าทั้งหมด
app.get("/api/products", async (req, res) => {
const { rows } = await pool.query("select * from products order by id");
res.json(rows);
});
// GET /api/products/1 → สินค้า 1 ชิ้น
app.get("/api/products/:id", async (req, res) => {
const { rows } = await pool.query("select * from products where id = $1", [req.params.id]);
if (!rows.length) return res.status(404).json({ error: "Not found" });
res.json(rows[0]);
});
// POST /api/orders → สร้างออเดอร์
// body: { "customerName": "Natch", "items": [{ "productId": 1, "quantity": 2 }] }
app.post("/api/orders", async (req, res) => {
const { customerName, items } = req.body;
const client = await pool.connect();
try {
await client.query("begin");
const order = await client.query(
"insert into orders (customer_name) values ($1) returning id",
[customerName],
);
const orderId = order.rows[0].id;
let total = 0;
for (const item of items) {
const p = await client.query("select price from products where id = $1", [item.productId]);
const price = Number(p.rows[0].price);
total += price * item.quantity;
await client.query(
"insert into order_items (order_id, product_id, quantity, price) values ($1, $2, $3, $4)",
[orderId, item.productId, item.quantity, price],
);
}
await client.query("update orders set total = $1 where id = $2", [total, orderId]);
await client.query("commit");
res.status(201).json({ id: orderId, total });
} catch (err) {
await client.query("rollback");
res.status(400).json({ error: err.message });
} finally {
client.release();
}
});
const port = process.env.PORT || 4000;
app.listen(port, () => console.log("API running on http://localhost:" + port));ทำไมใช้ $1ใช้ $1, $2 แทนการต่อ string เสมอ เพื่อกัน SQL injection
| ใน handler | ได้อะไร |
|---|---|
req.params.id | ค่าใน URL เช่น /api/products/:id |
req.query.color | ค่าหลัง ? เช่น ?color=red |
req.body | JSON ที่ส่งมากับ POST / PATCH |
res.json(data) | ตอบกลับเป็น JSON |
res.status(404) | ตั้ง status code |
รันและทดสอบ
npm run dev # รันเซิร์ฟเวอร์
curl http://localhost:4000/api/products # ทดสอบ GET
curl -X POST http://localhost:4000/api/orders \
-H "Content-Type: application/json" \
-d '{"customerName":"Natch","items":[{"productId":1,"quantity":2}]}'หรือเปิด Thunder Client ใน IDE กด New Request ใส่ URL และ body แล้วกด Send
ฝึกต่อ
เว็บสำหรับลงมือทำ
เอกสาร · expressjs.comExpress: Getting started เอกสารทางการเอกสาร · node-postgres.comnode-postgres (pg) วิธี query และ transactionลงมือทำ · developer.mozilla.orgMDN: Express tutorial ทำโปรเจกต์ library ทีละบทเอกสาร · vercel.comExpress on Vercel deploy API ขึ้น Vercel
วิดีโอเรียนเอง
Next steps
- Node.js: เข้าใจตัวที่รัน Express
- Challenge Day 3: ต่อ API เข้ากับหน้าร้าน
CS ChallengeLast updated Oct 2026

