ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Routing ဆိုတာ စာတိုက်က စာခွဲတဲ့ အလုပ်လိုပါပဲ။ စာအိတ်ပေါ်မှာ "GET /products/15" လို့ ရေးထားရင် method (GET) နဲ့ လိပ်စာ (/products/15) ကိုကြည့်ပြီး ဘယ်ဌာနကို ပို့ရမလဲ ဆုံးဖြတ်ပါတယ်။ /products/15၊ /products/16၊ /products/99 အားလုံး ဌာနတစ်ခုတည်းကို ရောက်ပြီး ဌာနက လိပ်စာထဲက နံပါတ်ကိုကြည့်ကာ ပစ္စည်းကို ရှာပါတယ်။
Express မှာ အဲဒီ "နံပါတ် နေရာ" ကို /products/:id လို့ ရေးပြီး ဌာနတွေကို express.Router() နဲ့ ဖွဲ့ပါတယ်။ ?maxPrice=30 လို စာအိတ်ပေါ်က မှတ်ချက်တွေက query string ဖြစ်ပြီး စာအိတ်ထဲက စာရွက် (POST နဲ့ ပို့တဲ့ JSON) ကတော့ request body ပါ။
Problem → Why → Solution
ပြဿနာ: id တစ်ခုစီအတွက် route တစ်ခုစီ
Product ဆယ်ခုရှိတဲ့ shop အတွက် route ရေးတော့ /products/1၊ /products/2 လို့ တစ်ခုချင်း ရေးမိတယ် ဆိုပါစို့။ Product အသစ် ထည့်တိုင်း code ပြင်ရပြီး deploy ပြန်လုပ်ရပါတယ်။ POST route မှာလည်း req.body ကို ဖတ်ဖို့ ကြိုးစားတော့ "Cannot destructure property 'name' of 'req.body' as it is undefined" ဆိုတဲ့ TypeError ရပါတယ်။ Route တွေ ရာချီ ရှိလာတဲ့အခါ app.js file တစ်ခုတည်းထဲမှာ အကုန် စုထားတာလည်း ပြဿနာ ဖြစ်လာပါတယ်။
app.get('/products/1', (req, res) => res.json(products[0]));
app.get('/products/2', (req, res) => res.json(products[1]));
// ...one route per product, forever
app.post('/products', (req, res) => {
const { name, price } = req.body; // TypeError: req.body is undefined
res.json({ name, price }); // (express.json() was never added)
});ဘာကြောင့် ဒီလို ဖြစ်တာလဲ
URL ထဲက ပြောင်းလဲနေတဲ့ အပိုင်း (id) ကို pattern အဖြစ် မရေးဘဲ value တစ်ခုချင်းကို route အဖြစ် ရေးလိုက်လို့ပါ။ :id လို route parameter တစ်ခုက id အားလုံးကို route တစ်ခုတည်းနဲ့ ဖမ်းပေးပါတယ်။ Body ကတော့ stream အနေနဲ့ ရောက်လာတာမို့ Express က ကိုယ်တိုင် မဖတ်ပေးပါဘူး — express.json() middleware ကို ထည့်မှ JSON ကို parse လုပ်ပြီး req.body ထဲ ထည့်ပေးပါတယ်။ Body parser မရှိရင် req.body က undefined ဖြစ်ပြီး Express 5 မှာ express.json() ရှိပေမယ့် JSON body မပါတဲ့ request အတွက်လည်း undefined ပဲ ဖြစ်ပါတယ်။
Core concept: request ရဲ့ အပိုင်းသုံးပိုင်းနဲ့ Router
Route တစ်ခုကို app.METHOD(path, handler) ပုံစံနဲ့ ရေးပါတယ်၊ Express က method နဲ့ path နှစ်ခုလုံး ကိုက်တဲ့ ပထမဆုံး route ကို ရွေးပါတယ်။ Path ထဲမှာ : နဲ့ စတဲ့ အပိုင်းက route parameter ဖြစ်ပြီး /products/:id က /products/15 နဲ့ ကိုက်ကာ req.params.id ကို '15' လို့ ပေးပါတယ်။ Parameter value တွေက အမြဲ string ဖြစ်လို့ number id နဲ့ နှိုင်းယှဉ်ချင်ရင် Number() နဲ့ ပြောင်းရပါမယ် — '15' === 15 က false ပါ။ Parameter တစ်ခုက / ကို မကျော်ပါဘူး၊ ဒါကြောင့် /products/:id က /products/1/reviews နဲ့ မကိုက်ပါဘူး။
Request ကနေ data ရနိုင်တဲ့ နေရာ သုံးခု ရှိပါတယ်။ req.params က path ထဲက :name အပိုင်းတွေ၊ req.query က ? နောက်က query string (/products?maxPrice=30 ဆို { maxPrice: '30' })၊ req.body က POST/PUT/PATCH နဲ့ ပို့တဲ့ body ပါ။ Resource တစ်ခုကို ရွေးတာ (ဘယ် product လဲ) ဆို params၊ list ကို filter/sort/page ခွဲတာ ဆို query၊ data အသစ် ပို့တာဆို body ကို သုံးတာ ပုံမှန်ပါပဲ။ Body က express.json() ကို app.use() နဲ့ ထည့်ထားမှ ရပါတယ်။
express.Router() က route တွေကို စုထားတဲ့ app အသေးလေး တစ်ခုပါ။ Router ပေါ်မှာ router.get('/:id') လို့ prefix မပါဘဲ ရေးပြီး app.use('/products', router) နဲ့ mount လုပ်လိုက်ရင် Express က /products ကို ရှေ့က ထည့်ပေးပါတယ်။ ဒါကြောင့် products.js၊ users.js လို file တစ်ခုစီမှာ resource တစ်ခုစီရဲ့ route တွေကို သီးသန့် ထားလို့ ရပါတယ်။
Method တစ်ခုစီက အဓိပ္ပာယ် ကိုယ်စီ ရှိပါတယ် — GET က ဖတ်တာ၊ POST က အသစ် ဖန်တီးတာ၊ PUT က တစ်ခုလုံး အစားထိုးတာ၊ PATCH က တစ်စိတ်တစ်ပိုင်း ပြင်တာ၊ DELETE က ဖျက်တာပါ။ ဒါကြောင့် /products/:id ဆိုတဲ့ path တစ်ခုတည်းမှာ router.get()၊ router.put()၊ router.delete() handler သုံးခု သီးသန့် ရှိနိုင်ပြီး Express က method ကိုကြည့်ပြီး ခွဲပေးပါတယ်။
Parameter လေးခုပါတဲ့ (err, req, res, next) middleware က error handler ပါ။ Handler တစ်ခုက next(err) ခေါ်တာ၊ synchronous error throw လုပ်တာ ဒါမှမဟုတ် Express 5 မှာ async handler ရဲ့ Promise reject ဖြစ်တာ ဆိုရင် Express က ကျန်တဲ့ route တွေကို ကျော်ပြီး ဒီ handler ဆီ တိုက်ရိုက် ပို့ပါတယ်။ Express 4 မှာတော့ async error ကို ကိုယ်တိုင် try/catch လုပ်ပြီး next(err) ခေါ်ရပါတယ်၊ မဟုတ်ရင် request က တန်းလန်း ကျန်ခဲ့ပါတယ်။
- Mount prefix ကို ဖယ် (/products)
- ကျန်တဲ့ path ကို pattern နဲ့ ယှဉ်
- :id → req.params၊ ?x → req.query
- Error ဆို 4-arg handler ဆီ ခုန်
params နဲ့ query value တွေက အမြဲ string ပါ၊ body ကတော့ express.json() parse လုပ်ပေးတဲ့ JSON type အတိုင်း ရပါတယ်။
အထွေထွေ ပုံစံ
const router = express.Router();
router.get('/', handler); // GET /prefix?key=value -> req.query
router.get('/:param', handler); // GET /prefix/abc -> req.params
router.post('/', handler); // POST /prefix + body -> req.body
app.use(express.json()); // parse JSON bodies first
app.use('/prefix', router); // mount the router
app.use((err, req, res, next) => { /* one place for errors */ });Router ပေါ်က path တွေက mount prefix နဲ့ ဆက်စပ်ပါတယ်။ express.json() ကို router ရဲ့ အပေါ်မှာ၊ error handler ကို အားလုံးရဲ့ အောက်ဆုံးမှာ ထားပါ။
Example: products router တစ်ခု
Router တစ်ခုထဲမှာ query နဲ့ filter လုပ်တဲ့ list route၊ :id နဲ့ product တစ်ခု ရှာတဲ့ route၊ JSON body နဲ့ product အသစ် ဖန်တီးတဲ့ POST route နဲ့ error throw လုပ်တဲ့ async route ပါပါတယ်။ fetch နဲ့ request ငါးခု ပို့ပြီး status နဲ့ body ကို print ထုတ်ပါတယ်။ နောက်ဆုံး line မှာ async error က error handler ကနေ 500 JSON အဖြစ် ထွက်လာတာကို သတိထားကြည့်ပါ။
import express from 'express';
const products = [
{ id: 1, name: 'Keyboard', price: 45 },
{ id: 2, name: 'Mouse', price: 20 },
];
async function loadReviews(id) {
throw new Error(`Review service is down (product ${id})`);
}
const router = express.Router();
router.get('/', (req, res) => {
const max = Number(req.query.maxPrice ?? Infinity);
res.json(products.filter((p) => p.price <= max));
});
router.get('/:id', (req, res) => {
const product = products.find((p) => p.id === Number(req.params.id));
if (!product) return res.status(404).json({ error: 'Product not found' });
res.json(product);
});
router.post('/', (req, res) => {
const { name, price } = req.body;
const product = { id: products.length + 1, name, price: Number(price) };
products.push(product);
res.status(201).json(product);
});
router.get('/:id/reviews', async (req, res) => {
res.json(await loadReviews(req.params.id)); // Express 5 forwards the rejection
});
const app = express();
app.use(express.json());
app.use('/products', router);
app.use((err, req, res, next) => res.status(500).json({ error: err.message }));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const call = async (method, path, body) => {
const res = await fetch(base + path, {
method,
headers: { 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
});
console.log(`${method} ${path} -> ${res.status} ${await res.text()}`);
};
await call('GET', '/products?maxPrice=30');
await call('GET', '/products/2');
await call('GET', '/products/99');
await call('POST', '/products', { name: 'Monitor', price: 150 });
await call('GET', '/products/1/reviews');
server.close();
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Query string
const max = Number(req.query.maxPrice ?? Infinity);?maxPrice=30 က req.query.maxPrice ကို string '30' အဖြစ် ပေးလို့ Number() နဲ့ ပြောင်းပါတယ်။ Query မပါရင် Infinity ကို သုံးလို့ product အားလုံး ပြန်ရပါတယ်။
- Route parameter + 404
if (!product) return res.status(404).json({ error: 'Product not found' });/products/99 ကို ရှာမတွေ့လို့ 404 ပြန်ပါတယ်။ return ပါလို့ အောက်က res.json(product) ကို ဆက် မ run တော့ပါဘူး။
- JSON body
const { name, price } = req.body;express.json() က body ကို parse လုပ်ပေးထားလို့ ဖတ်လို့ ရပါတယ်။ Field တွေကို နာမည်နဲ့ ရွေးယူတာက client ပို့တဲ့ id လို field မျိုးကို ဖန်တီးမယ့် object ထဲ မရောက်အောင် ကာကွယ်ပါတယ်။
- 201 Created
res.status(201).json(product);အရာအသစ် ဖန်တီးပြီးတဲ့အခါ 200 အစား 201 ကို ပြန်ပေးပြီး ဖန်တီးလိုက်တဲ့ object (id အသစ်ပါ) ကို body အဖြစ် ပို့ပါတယ်။
- Async error
res.json(await loadReviews(req.params.id)); // Express 5 forwards the rejectionloadReviews() reject ဖြစ်လို့ handler ရဲ့ Promise လည်း reject ဖြစ်ပါတယ်။ Express 5 က next(err) ကို ကိုယ်တိုင် ခေါ်ပေးလို့ error handler က 500 JSON ပြန်ပါတယ် — try/catch မလိုပါဘူး။
- Error handler
app.use((err, req, res, next) => res.status(500).json({ error: err.message }));Parameter လေးခု ပါလို့ Express က error handler အဖြစ် သိပါတယ်။ next ကို မသုံးပေမယ့် ဖြုတ်လို့ မရပါဘူး — parameter သုံးခုပဲ ဆိုရင် ရိုးရိုး middleware ဖြစ်သွားပါတယ်။
GET /products?maxPrice=30 -> 200 [{"id":2,"name":"Mouse","price":20}]
GET /products/2 -> 200 {"id":2,"name":"Mouse","price":20}
GET /products/99 -> 404 {"error":"Product not found"}
POST /products -> 201 {"id":3,"name":"Monitor","price":150}
GET /products/1/reviews -> 500 {"error":"Review service is down (product 1)"}Express 5 ရဲ့ path syntax
Express 5 က path-to-regexp library အသစ်ကို သုံးလို့ Express 4 tutorial ဟောင်းတွေက pattern တချို့ မအလုပ်လုပ်တော့ပါဘူး။ Wildcard ကို နာမည်ပေးရပြီး (/files/*splat)၊ optional အပိုင်းကို {} နဲ့ ရေးရပါတယ်။ app.get('/a/*', ...) လို နာမည်မပါတဲ့ * ကို ရေးရင် app start ချိန်မှာပဲ "Missing parameter name" error တက်ပါတယ်။
| Pattern | ကိုက်တဲ့ URL | req.params |
|---|---|---|
| /users/:id | /users/7 | { id: '7' } |
| /files/*splat | /files/a/b/c | { splat: ['a', 'b', 'c'] } |
| /posts{/:slug} | /posts နဲ့ /posts/hello | {} / { slug: 'hello' } |
လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
REST API တစ်ခုမှာ resource တစ်ခုစီ (users၊ orders၊ products) က router file တစ်ခုစီ ရပြီး app.js က app.use('/api/users', usersRouter) လို mount line တွေပဲ ပါပါတယ်။ GET /api/orders?status=paid&page=2 လို list endpoint တွေက filter နဲ့ pagination ကို query ကနေ ဖတ်ပြီး GET /api/orders/:id က order တစ်ခုကို ပြန်ပေးပါတယ်။ POST က 201၊ မတွေ့ရင် 404၊ data မှားရင် 400 ဆိုတဲ့ status code စည်းမျဉ်းကို API တစ်ခုလုံး တသမတ်တည်း လိုက်နာတာက frontend developer တွေအတွက် အရမ်း အရေးကြီးပါတယ်။
Error handler တစ်ခုတည်းကလည်း production မှာ အသုံးဝင်ပါတယ်။ Error တိုင်းကို logging service ဆီ ပို့တာ၊ client ကိုတော့ stack trace မပြဘဲ ယေဘုယျ message ပဲ ပြန်တာ စတဲ့ policy ကို တစ်နေရာတည်းမှာ ချမှတ်လို့ ရပါတယ်။ Express 5 ရဲ့ async error forwarding ကြောင့် database query လုပ်တဲ့ route တိုင်းမှာ try/catch ထပ်ခါထပ်ခါ ရေးစရာ မလိုတော့ပါဘူး။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. req.params.id ကို number နဲ့ === ယှဉ်တာ
products.find((p) => p.id === req.params.id) က '2' === 2 ဖြစ်လို့ ဘယ်တော့မှ မတွေ့ဘဲ id တိုင်းအတွက် 404 ရပါတယ်။ Number(req.params.id) နဲ့ ပြောင်းပြီး Number.isInteger() နဲ့ စစ်ကာ မမှန်ရင် 400 ပြန်ပါ။
2. Specific route ကို :param route အောက်မှာ ထားတာ
router.get('/:id') ကို router.get('/featured') ရဲ့ အပေါ်မှာ ရေးရင် /products/featured က :id = 'featured' အဖြစ် ပထမ route နဲ့ ကိုက်သွားလို့ featured route ဆီ ဘယ်တော့မှ မရောက်ပါဘူး။ Fixed path တွေကို parameter route တွေရဲ့ အပေါ်မှာ ထားပါ။
3. Error handler မှာ parameter သုံးခုပဲ ရေးတာ
(err, req, res) => ... ဆိုရင် Express က parameter အရေအတွက်ကိုကြည့်ပြီး ရိုးရိုး middleware လို့ ယူဆလို့ error တွေ ဒီကို မရောက်ဘဲ default HTML error page ပဲ ထွက်ပါတယ်။ next ကို မသုံးလည်း parameter လေးခုလုံး ရေးပါ။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- URL path တွေမှာ နာမ် အများကိန်း (/products၊ /orders) ကို သုံးပြီး လုပ်ဆောင်ချက်ကို method နဲ့ ဖော်ပြပါ (/getProducts လို မရေးပါနဲ့)။
- params၊ query နဲ့ body ကနေ ရတဲ့ value တိုင်းကို type ပြောင်းပြီး စစ်ပါ၊ မမှန်ရင် 400 နဲ့ ဘာမှားလဲ ပြောပါ။
- Router file တစ်ခုစီကို resource တစ်ခုစီအတွက် ထားပြီး app.js မှာ mount line တွေပဲ ချန်ထားပါ။
Mini challenge
Mini challenge: todos router
/api/todos အောက်မှာ mount လုပ်ထားတဲ့ router တစ်ခုနဲ့ todo list API ရေးပြီး fetch နဲ့ request ခြောက်ခု ပို့ကာ စမ်းပါ။
- GET / က todo အားလုံး၊ ?done=true ပါရင် ပြီးသွားတဲ့ todo တွေပဲ ပြန်ရမယ်
- GET /:id က todo တစ်ခု ပြန်ရမယ်၊ မရှိရင် 404
- POST / က title မပါရင် 400၊ ပါရင် 201 နဲ့ todo အသစ် ပြန်ရမယ်
- DELETE /:id က 204 (body မပါ) ပြန်ရမယ်၊ မရှိရင် 404
import express from 'express';
const todos = [{ id: 1, title: 'Learn routing', done: true },
{ id: 2, title: 'Build an API', done: false }];
const todosRouter = express.Router();
// TODO: GET / (?done=true filter; query values are strings)
// TODO: GET /:id (404 when missing)
// TODO: POST / (400 without title, else 201)
// TODO: DELETE /:id (204, or 404 when missing)
const app = express();
// TODO: express.json(), then mount todosRouter at /api/todos
const server = app.listen(0, async () => {
// TODO: send the six requests, print "<METHOD> <path> -> <status> <body>", close
});ရလဒ်: ရရမယ့် output: GET /api/todos?done=true -> 200 [{"id":1,"title":"Learn routing","done":true}] GET /api/todos/2 -> 200 {"id":2,"title":"Build an API","done":false} POST /api/todos -> 400 {"error":"title is required"} POST /api/todos -> 201 {"id":3,"title":"Write tests","done":false} DELETE /api/todos/1 -> 204 GET /api/todos/1 -> 404 {"error":"Todo not found"}
အရိပ်အမြွက် ကြည့်ရန်
req.query.done က string 'true' ဖြစ်လို့ req.query.done === 'true' လို့ စစ်ပါ။ Body မပါတဲ့ 204 အတွက် res.sendStatus(204) ဒါမှမဟုတ် res.status(204).end() ကို သုံးပါ။ ဖျက်ဖို့ findIndex() နဲ့ splice() ကို သုံးနိုင်ပါတယ်။
အဖြေ ကြည့်ရန်
import express from 'express';
const todos = [{ id: 1, title: 'Learn routing', done: true },
{ id: 2, title: 'Build an API', done: false }];
let nextId = 3;
const todosRouter = express.Router();
todosRouter.get('/', (req, res) => {
const onlyDone = req.query.done === 'true';
res.json(onlyDone ? todos.filter((t) => t.done) : todos);
});
todosRouter.get('/:id', (req, res) => {
const todo = todos.find((t) => t.id === Number(req.params.id));
if (!todo) return res.status(404).json({ error: 'Todo not found' });
res.json(todo);
});
todosRouter.post('/', (req, res) => {
const title = req.body?.title;
if (!title) return res.status(400).json({ error: 'title is required' });
const todo = { id: nextId++, title, done: false };
todos.push(todo);
res.status(201).json(todo);
});
todosRouter.delete('/:id', (req, res) => {
const index = todos.findIndex((t) => t.id === Number(req.params.id));
if (index === -1) return res.status(404).json({ error: 'Todo not found' });
todos.splice(index, 1);
res.sendStatus(204);
});
const app = express();
app.use(express.json());
app.use('/api/todos', todosRouter);
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const requests = [['GET', '/api/todos?done=true'], ['GET', '/api/todos/2'],
['POST', '/api/todos', {}], ['POST', '/api/todos', { title: 'Write tests' }],
['DELETE', '/api/todos/1'], ['GET', '/api/todos/1']];
for (const [method, path, body] of requests) {
const res = await fetch(base + path, {
method,
headers: { 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
});
console.log(`${method} ${path} -> ${res.status} ${await res.text()}`);
}
server.close();
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- app.METHOD(path, handler) မှာ method နဲ့ path နှစ်ခုလုံး ကိုက်တဲ့ ပထမ route က ဖြေတယ်။
- req.params က path ထဲက :name၊ req.query က ? နောက်က string၊ req.body က express.json() parse လုပ်ထားတဲ့ body ပါ။
- express.Router() နဲ့ resource တစ်ခုချင်းရဲ့ route တွေကို စုပြီး app.use('/prefix', router) နဲ့ mount လုပ်ပါ။
- Express 5 မှာ async error တွေက (err, req, res, next) handler ဆီ အလိုအလျောက် ရောက်တယ်။
Routing — Express.js