/Projects
Express
ProjectsCS ChallengeFull-StackExpress

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

  1. สร้างโปรเจกต์ Node.js

    mkdir server && cd server
    npm init -y
  2. ติดตั้ง package

    npm install express pg cors dotenv
    npm install -D nodemon
    Packageทำอะไร
    expressเว็บเซิร์ฟเวอร์และ routing
    pgตัวเชื่อม Node.js กับ PostgreSQL
    corsอนุญาตให้หน้าเว็บ (localhost:3000) เรียก API ได้
    dotenvอ่านค่าจากไฟล์ .env
    nodemonเซฟแล้วรีสตาร์ตเซิร์ฟเวอร์เอง
  3. ตั้งค่า package.json

    เพิ่ม "type": "module" และ script สำหรับรัน

    {
      "type": "module",
      "scripts": {
        "dev": "nodemon index.js",
        "start": "node index.js"
      }
    }
  4. ใส่ connection string

    เอา URI จาก PostgreSQL › Installation ใส่ในไฟล์ .env และใส่ .env ใน .gitignore

    DATABASE_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.bodyJSON ที่ส่งมากับ 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

ฝึกต่อ

เว็บสำหรับลงมือทำ

วิดีโอเรียนเอง

Next steps

  • Node.js: เข้าใจตัวที่รัน Express
  • Challenge Day 3: ต่อ API เข้ากับหน้าร้าน
CS ChallengeLast updated Oct 2026