ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
http module နဲ့ server ရေးတာက ကောင်တာမှာ စာရွက်တိုင်းကို ကိုယ်တိုင် ဖတ်၊ ကိုယ်တိုင် ခွဲ၊ ကိုယ်တိုင် ဖြေရတာလိုပါ။ Express ကတော့ ကောင်တာမှာ "GET /health လာရင် ဒီလူဆီ ပို့"၊ "POST /orders လာရင် ဟိုလူဆီ ပို့" ဆိုတဲ့ ညွှန်ကြားချက် ဘုတ်တစ်ခု ချိတ်ပေးတာပါ။ စာရွက် ဝင်လာတိုင်း Express က ဘုတ်ကိုကြည့်ပြီး မှန်ကန်တဲ့ function ဆီ လွှဲပေးပါတယ်။
အဖြေ ပြန်ပေးရတာလည်း ပိုလွယ်ပါတယ်။ res.json({ status: 'ok' }) လို့ ရေးလိုက်ရင် Express က object ကို JSON string ပြောင်း၊ Content-Type header ထည့်၊ response ကို ပိတ်ပေးပါတယ်။ Express က http module ကို အစားထိုးတာ မဟုတ်ပါဘူး — အပေါ်ကနေ အထောက်အကူ အလွှာတစ်ခု ထပ်ထည့်ထားတာပါ။
Problem → Why → Solution
ပြဿနာ: if ကွင်းဆက်က ရှည်လာတယ်
ယခင် lesson ရဲ့ raw http server မှာ route တစ်ခု ထပ်ထည့်တိုင်း else if တစ်ခု ထပ်ရေးရပြီး JSON ပြန်ပေးတိုင်း writeHead၊ Content-Type၊ JSON.stringify ကို ထပ်ခါထပ်ခါ ရေးရပါတယ်။ Request တိုင်းကို log ထုတ်ချင်ရင် branch တိုင်းမှာ console.log ထည့်ရမလား ဆိုတဲ့ မေးခွန်း ပေါ်လာပါတယ်။ Route ဆယ်ခုလောက် ရောက်တာနဲ့ handler တစ်ခုတည်းက ဖတ်ရခက်၊ ပြင်ရခက်တဲ့ function ရှည်ကြီး ဖြစ်သွားပါတယ်။
http.createServer((req, res) => {
console.log(req.method, req.url); // logging, mixed into routing
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
} else if (req.method === 'GET' && req.url === '/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(users));
} else if (/* ...eight more routes... */ false) {
} else {
res.writeHead(404); res.end();
}
});ဘာကြောင့် framework တစ်ခု လိုလာတာလဲ
Routing (ဘယ် request ကို ဘယ် code က ကိုင်မလဲ)၊ cross-cutting အလုပ် (log ထုတ်တာ၊ body parse လုပ်တာ၊ auth စစ်တာ)၊ response ပို့တာ ဆိုတဲ့ တာဝန် သုံးမျိုးလုံး function တစ်ခုထဲမှာ ရောနေလို့ပါ။ Express က route တစ်ခုချင်းကို function သီးသန့် ပေးပြီး request တိုင်းအတွက် လုပ်ရမယ့် အလုပ်တွေကို middleware အဖြစ် ခွဲထုတ်ပေးတာမို့ code တစ်ပိုင်းချင်းက တာဝန်တစ်ခုတည်းပဲ ယူပါတော့တယ်။
Core concept: app၊ route နဲ့ middleware ကွင်းဆက်
const app = express() က application object တစ်ခု ဆောက်ပေးပါတယ်။ app.get(path, handler)၊ app.post()၊ app.put()၊ app.delete() တို့က "ဒီ method နဲ့ ဒီ path လာရင် ဒီ handler ကို ခေါ်" ဆိုတဲ့ route တွေ မှတ်ပုံတင်ပါတယ်။ app.listen(port, callback) က အတွင်းမှာ http.createServer(app) ကို ခေါ်ပြီး ရလာတဲ့ http.Server ကို ပြန်ပေးလို့ ယခင် lesson မှာ သုံးခဲ့တဲ့ server.address() နဲ့ server.close() ကို ဆက်သုံးလို့ ရပါတယ်။
Express က req နဲ့ res ကို helper တွေနဲ့ ချဲ့ထားပါတယ်။ res.send(value) က value အမျိုးအစားကိုကြည့်ပြီး Content-Type ရွေးပါတယ် — string ဆို text/html၊ object ဒါမှမဟုတ် array ဆို JSON ပါ။ res.json(value) က အမြဲ JSON ပို့ပြီး res.status(404) က status ကို သတ်မှတ်ကာ res ကို ပြန်ပေးလို့ res.status(404).json({...}) လို ဆက်ရေးလို့ ရပါတယ်။ req.path က query string မပါတဲ့ path ဖြစ်ပြီး req.query က query string ကို object အဖြစ် ပြောင်းပေးပါတယ်။
Middleware ဆိုတာ (req, res, next) parameter သုံးခုပါတဲ့ function ပါ။ app.use(fn) နဲ့ မှတ်ပုံတင်ပြီး request တိုင်း ဖြတ်သွားပါတယ်။ Middleware တစ်ခုက response ကို ကိုယ်တိုင် ပို့နိုင်သလို next() ကိုခေါ်ပြီး နောက် middleware ဒါမှမဟုတ် route ဆီ လွှဲပေးနိုင်ပါတယ်။ နှစ်ခုလုံး မလုပ်ရင် request က တန်းလန်း ကျန်နေပါတယ်။ Express က middleware နဲ့ route တွေကို မှတ်ပုံတင်ခဲ့တဲ့ အစဉ်အတိုင်း စမ်းတာမို့ logger ကို အပေါ်ဆုံးမှာ၊ 404 handler ကို အောက်ဆုံးမှာ ထားရပါတယ်။
ဒီ tutorial က Express 5 ကို သုံးပါတယ်။ Express 5 က Node 18 နဲ့ အထက်ကို လိုအပ်ပြီး async handler ထဲမှာ throw လုပ်တဲ့ error (reject ဖြစ်တဲ့ Promise) ကို error-handling middleware ဆီ အလိုအလျောက် ပို့ပေးပါတယ်။ Express 4 မှာတော့ အဲဒီအတွက် try/catch နဲ့ next(err) ကို ကိုယ်တိုင် ရေးခဲ့ရပါတယ် — နောက် lesson မှာ အသေးစိတ် ကြည့်ပါမယ်။
Express ကို npm install express နဲ့ project ထဲ ထည့်ပါ — Node.js နဲ့ အတူ ပါမလာတဲ့ package ပါ။ Route path တစ်ခုက method နဲ့ path နှစ်ခုလုံး ကိုက်မှ အလုပ်လုပ်တာမို့ app.get('/health') က POST /health ကို မဖြေပါဘူး၊ request က အောက်ကို ဆက်သွားပြီး 404 handler ဆီ ရောက်ပါတယ်။
- Request ဝင်လာ
- Middleware တွေ အစဉ်လိုက် run (next)
- ကိုက်တဲ့ ပထမ route က ဖြေ
- ဘာမှ မကိုက်ရင် 404 handler
Response ပို့ပြီးတာနဲ့ ကွင်းဆက် ရပ်ပါတယ်၊ အောက်က route တွေကို ဆက်မစမ်းတော့ပါဘူး။
အထွေထွေ ပုံစံ
import express from 'express';
const app = express();
app.use((req, res, next) => { /* every request */ next(); });
app.METHOD('/path', (req, res) => {
res.status(CODE).json(data); // or res.send(text)
});
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
const server = app.listen(PORT, () => { /* ready */ });အစဉ်က အရေးကြီးပါတယ် — request တိုင်းအတွက် middleware၊ ပြီးရင် route တွေ၊ နောက်ဆုံးမှ 404 fallback ပါ။ METHOD နေရာမှာ get၊ post၊ put၊ patch၊ delete ကို သုံးပါ။
Example: logger၊ route နှစ်ခုနဲ့ 404
ဒီ app မှာ request တိုင်းကို log ထုတ်တဲ့ middleware၊ text ပြန်တဲ့ home route၊ JSON ပြန်တဲ့ /health route နဲ့ JSON 404 handler ပါပါတယ်။ Port 0 ပေါ်မှာ ဖွင့်ပြီး fetch နဲ့ request သုံးခု ပို့ပါတယ်။ [server] line တွေက middleware ကနေ၊ [client] line တွေက fetch ရလဒ်ကနေ လာတာမို့ request တစ်ခုချင်းရဲ့ ခရီးကို အစဉ်လိုက် မြင်ရပါတယ်။
import express from 'express';
const app = express();
// Middleware: runs for every request, then hands over with next()
app.use((req, res, next) => {
console.log(`[server] ${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'nodejs-tutorial' });
});
// Registered last: only reached when no route above answered
app.use((req, res) => {
res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/', '/health', '/admin']) {
const res = await fetch(base + path);
const type = res.headers.get('content-type');
console.log(`[client] ${res.status} ${type} ${await res.text()}`);
}
server.close();
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Middleware
app.use((req, res, next) => {Path မပေးထားလို့ request တိုင်းအတွက် run ပါတယ်။ log ထုတ်ပြီး next() ခေါ်လို့ request က အောက်က route တွေဆီ ဆက်သွားပါတယ်။
- Text response
res.send('Hello from Express!');String ကို ပို့တာမို့ Express က Content-Type ကို text/html; charset=utf-8 လို့ သတ်မှတ်ပါတယ် — output မှာ မြင်ရပါတယ်။ Status ကို မသတ်မှတ်ရင် 200 ပါ။
- JSON response
res.json({ status: 'ok', service: 'nodejs-tutorial' });JSON.stringify နဲ့ application/json header ကို Express က လုပ်ပေးပါတယ်။ Raw http မှာ line နှစ်ကြောင်း လိုခဲ့တာ ဒီမှာ တစ်ကြောင်းပါ။
- 404 fallback
res.status(404).json({ error: `No route for ${req.method} ${req.path}` });အောက်ဆုံးမှာ ရှိလို့ အပေါ်က route တစ်ခုမှ မဖြေမှသာ ရောက်ပါတယ်။ ဒီ handler မရှိရင် Express ရဲ့ default က "Cannot GET /admin" ဆိုတဲ့ HTML page ပါ။
- listen returns the server
const server = app.listen(0, async () => {app.listen() က http.Server ကို ပြန်ပေးလို့ port ကို ဖတ်ဖို့နဲ့ နောက်ဆုံးမှာ close() လုပ်ဖို့ variable ထဲ သိမ်းထားပါတယ်။
[server] GET /
[client] 200 text/html; charset=utf-8 Hello from Express!
[server] GET /health
[client] 200 application/json; charset=utf-8 {"status":"ok","service":"nodejs-tutorial"}
[server] GET /admin
[client] 404 application/json; charset=utf-8 {"error":"No route for GET /admin"}Raw http နဲ့ Express ကို ဘေးချင်းယှဉ်ကြည့်ခြင်း
Express က http module ကို ဖုံးကွယ်ထားတာ မဟုတ်ပါဘူး — req က http.IncomingMessage ဖြစ်နေဆဲ၊ res က http.ServerResponse ဖြစ်နေဆဲပါ။ ဒါကြောင့် res.setHeader() နဲ့ req.headers လို ယခင် lesson က အရာတွေ Express handler ထဲမှာ ဆက်အလုပ်လုပ်ပါတယ်။ Express က အပေါ်ကနေ ထပ်ထည့်ပေးတာတွေကို အောက်က ဇယားမှာ ယှဉ်ကြည့်နိုင်ပါတယ်။ Framework ကို ရွေးတာက raw http ကို မသိဘဲ ရှောင်တာ မဟုတ်ဘဲ ထပ်ခါထပ်ခါ ရေးရမယ့် code ကို လျှော့ချတာပါ။
| အလုပ် | Raw http | Express |
|---|---|---|
| Route ခွဲတာ | if (req.method === ... && req.url === ...) | app.get('/path', handler) |
| JSON ပို့တာ | writeHead + JSON.stringify + end | res.json(data) |
| Query ဖတ်တာ | new URL(req.url, base).searchParams | req.query |
| Request တိုင်း အလုပ် | Branch တိုင်းမှာ ထပ်ရေး | app.use(middleware) |
လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Express က Node.js မှာ အသုံးအများဆုံး web framework တွေထဲက တစ်ခုဖြစ်ပြီး REST API၊ mobile app backend၊ server-rendered website တွေမှာ တွေ့ရပါတယ်။ Production app တစ်ခုရဲ့ app.js ကို ဖွင့်ကြည့်ရင် အပေါ်ပိုင်းမှာ middleware စာရင်း ရှည်ရှည် တွေ့ရလေ့ ရှိပါတယ် — security header ထည့်တဲ့ helmet၊ cross-origin request ခွင့်ပြုတဲ့ cors၊ JSON body ဖတ်တဲ့ express.json()၊ request log ထုတ်တဲ့ logger စသဖြင့်ပါ။ အဲဒီ နောက်မှာ route တွေ၊ အောက်ဆုံးမှာ 404 နဲ့ error handler ပါပါတယ်။
/health လို endpoint ကလည်း အမှန်တကယ် အသုံးဝင်ပါတယ်။ Load balancer၊ Kubernetes နဲ့ uptime monitor တွေက ဒီ endpoint ကို စက္ကန့်အနည်းငယ်ခြား တစ်ခါ ခေါ်ပြီး 200 မရရင် instance ကို traffic ဖြတ်ပစ်တာ ဒါမှမဟုတ် restart လုပ်တာ ပြုလုပ်ပါတယ်။ Test တွေကလည်း ဒီ lesson လိုပဲ app ကို port 0 ပေါ်မှာ ဖွင့်ပြီး fetch နဲ့ စစ်ကြပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Middleware ထဲမှာ next() မေ့တာ
Logger middleware က console.log ပြီး next() မခေါ်ရင် request တိုင်း ဒီနေရာမှာ ရပ်နေပြီး browser က loading လုပ်နေပါတယ်။ Error message လည်း မပေါ်လို့ ရှာရ ခက်ပါတယ်။ Middleware တိုင်းက response ပို့တာ ဒါမှမဟုတ် next() ခေါ်တာ တစ်ခုခုကို အမြဲ လုပ်ရပါမယ်။
2. 404 handler ကို route တွေရဲ့ အပေါ်မှာ ထားတာ
app.use((req, res) => res.status(404)...) ကို app.get() တွေ မတိုင်ခင် ရေးမိရင် path မပါတဲ့ app.use() က request တိုင်းနဲ့ ကိုက်လို့ /health အပါအဝင် URL တိုင်း 404 ရပါတယ်။ Fallback တွေကို file ရဲ့ အောက်ဆုံးမှာ ထားပါ။
3. Response နှစ်ကြိမ် ပို့တာ
if (!user) res.status(404).json(...) ပြီးနောက် return မပါရင် code က ဆက် run ပြီး res.json(user) ကို ထပ်ခေါ်လို့ ERR_HTTP_HEADERS_SENT ရပါတယ်။ return res.status(404).json(...) လို့ ရေးပြီး handler ကို ချက်ချင်း ထွက်ပါ၊ ဒါမှ request တစ်ခုက response တစ်ခုတည်းပဲ ရပါတယ်။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- app ကို ဆောက်တဲ့ code နဲ့ app.listen() ကို file ခွဲထားပါ၊ ဒါမှ test တွေက port 0 ပေါ်မှာ app ကို ကိုယ်တိုင် ဖွင့်နိုင်ပါတယ်။
- API route တွေက JSON ပဲ ပြန်ပါစေ၊ 404 နဲ့ error တွေကိုလည်း { error: '...' } ပုံစံ တူတူနဲ့ ပြန်ပါ။
- Port နံပါတ်ကို process.env.PORT ကနေ ဖတ်ပြီး code ထဲမှာ ပုံသေ မရေးပါနဲ့။
Mini challenge
Mini challenge: request counter middleware
Request အရေအတွက်ကို ရေတွက်တဲ့ middleware၊ အဲဒီ အရေအတွက်ကို ပြတဲ့ /stats route နဲ့ JSON 404 handler ပါတဲ့ Express app တစ်ခု ရေးပြီး fetch နဲ့ စမ်းပါ။
- Middleware က request တိုင်းမှာ counter ကို တစ်တိုးပြီး next() ခေါ်ရမယ်
- GET / က 'Welcome' text ပြန်ရမယ်
- GET /stats က { requests: <count> } JSON ပြန်ရမယ်
- /, /nope, /stats ကို အစဉ်လိုက် ခေါ်ပြီး status နဲ့ body print ထုတ်ကာ server ပိတ်ရမယ်
import express from 'express';
const app = express();
let requests = 0;
// TODO: middleware that counts every request
// TODO: GET / -> 'Welcome'
// TODO: GET /stats -> { requests }
// TODO: 404 handler -> { error: 'Not found' } (registered last)
const server = app.listen(0, async () => {
// TODO: fetch '/', '/nope', '/stats'; print "<status> <body>"; close the server
});ရလဒ်: ရရမယ့် output: 200 Welcome 404 {"error":"Not found"} 200 {"requests":3}
အရိပ်အမြွက် ကြည့်ရန်
Counter middleware က route တွေ အပေါ်မှာ ရှိရပါမယ်၊ ဒါမှ 404 ဖြစ်တဲ့ /nope ကိုလည်း ရေတွက်ပါတယ်။ /stats ကို ခေါ်တဲ့ request ကိုယ်တိုင်လည်း handler မရောက်ခင် ရေတွက်ပြီးသား ဖြစ်ပါတယ်။
အဖြေ ကြည့်ရန်
import express from 'express';
const app = express();
let requests = 0;
app.use((req, res, next) => {
requests += 1;
next();
});
app.get('/', (req, res) => res.send('Welcome'));
app.get('/stats', (req, res) => res.json({ requests }));
app.use((req, res) => res.status(404).json({ error: 'Not found' }));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/', '/nope', '/stats']) {
const res = await fetch(base + path);
console.log(res.status, await res.text());
}
server.close();
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Express က http module ပေါ်မှာ routing၊ middleware နဲ့ response helper တွေ ထပ်ထည့်ပေးတဲ့ framework ပါ။
- app.METHOD(path, handler) နဲ့ route တွေ၊ app.use() နဲ့ middleware တွေ မှတ်ပုံတင်ပြီး အစဉ်လိုက် စမ်းတယ်။
- Middleware တိုင်း response ပို့တာ ဒါမှမဟုတ် next() ခေါ်တာ တစ်ခုခု လုပ်ရမယ်။
- res.json() နဲ့ res.status().json() က header နဲ့ stringify ကို ကိုင်ပေးပြီး 404 handler ကို အောက်ဆုံးမှာ ထားပါ။
Using middleware — Express.js