ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Web server တစ်ခုကို ဆိုင်ကောင်တာက ဝန်ထမ်းတစ်ယောက်လို့ မြင်ကြည့်ပါ။ Customer (browser) က "GET /about ပေးပါ" လို့ စာရွက်လေး ပို့လိုက်တယ်၊ ဝန်ထမ်းက စာရွက်ကိုဖတ်ပြီး အဖြေစာရွက်တစ်ရွက် ပြန်ပေးတယ်။ အဖြေစာရွက်ရဲ့ ထိပ်မှာ "200 OK" ဒါမှမဟုတ် "404 Not Found" လို အခြေအနေ ကုဒ်နဲ့ "ဒါ HTML ပါ" ဆိုတဲ့ label (header) တွေ ပါပြီး အောက်မှာ တကယ့် အကြောင်းအရာ (body) ပါပါတယ်။
Node.js ရဲ့ http module က အဲဒီ ကောင်တာကို ပေးပါတယ်။ ကိုယ်ကတော့ "စာရွက်တစ်ရွက် ရောက်လာတိုင်း ဘာလုပ်မလဲ" ဆိုတဲ့ function တစ်ခုကိုပဲ ရေးရပါတယ်။ Express လို framework တွေကလည်း အတွင်းမှာ ဒီ module ကိုပဲ သုံးတာမို့ ဒီမှာ နားလည်သမျှက နောက် lesson တွေမှာ တိုက်ရိုက် အသုံးဝင်ပါတယ်။
Problem → Why → Solution
ပြဿနာ: browser က ရပ်မနေဘဲ လည်နေတယ်
ပထမဆုံး server ကို ရေးတဲ့အခါ အဖြစ်များတာက တချို့ URL တွေမှာ browser က loading spinner လည်နေပြီး ဘာမှ မပြတာ၊ terminal ထဲမှာ ERR_HTTP_HEADERS_SENT error တက်ပြီး server crash ဖြစ်တာပါ။ အောက်က code မှာ /about branch က res.end() မခေါ်လို့ response မပြီးဆုံးပါဘူး၊ ဘယ် if နဲ့မှ မကိုက်တဲ့ URL တွေကလည်း အဖြေ လုံးဝ မရပါဘူး။ / ကို ခေါ်ရင်တော့ response ပြီးသွားပြီးမှ header ထပ်သတ်မှတ်လို့ error တက်ပါတယ်။
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/') {
res.end('Home');
}
if (req.url === '/about') {
res.write('About'); // no res.end(): the browser waits forever
}
// no fallback: /anything-else also hangs instead of returning 404
res.setHeader('X-App', 'demo'); // after '/' ended: ERR_HTTP_HEADERS_SENT
}).listen(3000);ဘာကြောင့် ဒီလို ဖြစ်တာလဲ
http module က response ကို stream တစ်ခုလို ကိုင်တွယ်ပါတယ်။ Header တွေက အရင်ဆုံး ထွက်သွားပြီး body က နောက်က လိုက်တယ်၊ res.end() ခေါ်မှ "ပြီးပြီ" လို့ client ကို ပြောပါတယ်။ ဒါကြောင့် request တိုင်းဟာ res.end() ကို တစ်ကြိမ်တည်း အတိအကျ ရောက်ရပြီး header တွေကို body မပို့ခင် သတ်မှတ်ပြီးသား ဖြစ်ရပါမယ်။ if/else if/else ကွင်းဆက်နဲ့ ရေးလိုက်ရင် လမ်းကြောင်းတိုင်း အဖြေတစ်ခုစီ ရပါတယ်။
Core concept: request တစ်ခု၊ handler ခေါ်မှု တစ်ကြိမ်
http.createServer(handler) က server object တစ်ခု ဆောက်ပေးပြီး request ဝင်လာတိုင်း handler(req, res) ကို ခေါ်ပါတယ်။ Server တစ်ခုက တစ်ပြိုင်နက် request ရာချီ လက်ခံနိုင်တာမို့ handler က အကြိမ်ရေ များစွာ ခေါ်ခံရပါတယ် — request တစ်ခုချင်းစီအတွက် req နဲ့ res အသစ် တစ်စုံစီ ရပါတယ်။ server.listen(port) ကို ခေါ်မှ server က port ပေါ်မှာ စောင့်နားထောင်ပြီး server.close() ခေါ်ရင် request အသစ် လက်ခံတာ ရပ်ပါတယ်။
req (IncomingMessage) က client ပို့လိုက်တာကို ဖော်ပြပါတယ်။ req.method က 'GET'၊ 'POST' လို စာလုံးကြီး string ဖြစ်ပြီး req.url က host မပါဘဲ path နဲ့ query string ပဲ ပါပါတယ် — ဥပမာ '/search?q=node'။ Query ကို ခွဲထုတ်ဖို့ new URL(req.url, 'http://localhost') လို့ ရေးပြီး searchParams.get('q') ကို သုံးပါတယ်။ req.headers ကတော့ header နာမည်တွေကို စာလုံးသေး key အဖြစ် ထားတဲ့ object ပါ။
res (ServerResponse) က ကိုယ်ပြန်ပို့မယ့် အဖြေပါ။ res.writeHead(status, headers) က status code နဲ့ header တွေကို တစ်ခါတည်း သတ်မှတ်ပြီး res.end(body) က body ကို ပို့ကာ response ကို ပိတ်ပါတယ်။ res.statusCode = 404 နဲ့ res.setHeader() ကို သီးသန့် သုံးလည်း ရပါတယ်။ Content-Type header က browser ကို body ကို ဘယ်လို နားလည်ရမလဲ ပြောတာမို့ HTML ဆို 'text/html; charset=utf-8'၊ JSON ဆို 'application/json' ပေးပါ — charset မပါရင် မြန်မာစာ လို UTF-8 စာတွေ ပျက်ပြီး ပေါ်နိုင်ပါတယ်။
| Status | ဘယ်အချိန် သုံးလဲ |
|---|---|
| 200 OK | Request အောင်မြင်ပြီး body ပါတယ် |
| 201 Created | POST နဲ့ အရာအသစ် ဖန်တီးပြီးပြီ |
| 400 Bad Request | Client ပို့တဲ့ data မှားနေတယ် |
| 404 Not Found | ဒီ URL မှာ ဘာမှ မရှိဘူး |
| 405 Method Not Allowed | URL ရှိပေမယ့် ဒီ method ကို လက်မခံဘူး |
| 500 Internal Server Error | Server ဘက်မှာ မမျှော်လင့်တဲ့ error |
Port နံပါတ်အနေနဲ့ 0 ပေးရင် operating system က အလွတ်ဖြစ်နေတဲ့ port တစ်ခုကို ရွေးပေးပြီး server.address().port ကနေ ပြန်ဖတ်လို့ ရပါတယ်။ Test တွေနဲ့ ဒီ lesson ရဲ့ example တွေမှာ port 3000 ကို တခြား program က သုံးနေလို့ EADDRINUSE error တက်တာကို ဒီနည်းနဲ့ ရှောင်ပါတယ်။
- Client က method + URL ပို့
- Handler က req.method/req.url စစ်
- writeHead() နဲ့ status + header
- end() နဲ့ body ပို့ပြီး ပိတ်
လမ်းကြောင်းတိုင်းက res.end() ကို တစ်ကြိမ်တည်း ရောက်ရပါမယ် — မရောက်ရင် client က စောင့်နေပြီး နှစ်ကြိမ်ဆိုရင် error တက်ပါတယ်။
အထွေထွေ ပုံစံ
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'METHOD' && req.url === '/path') {
res.writeHead(STATUS, { 'Content-Type': 'type' });
res.end(body);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});
server.listen(PORT, () => { /* ready */ });Handler တစ်ခုထဲမှာ method နဲ့ path ကိုစစ်ပြီး branch တိုင်းက writeHead() နဲ့ end() ကို တစ်ကြိမ်စီ ခေါ်ပါတယ်။ နောက်ဆုံး else က ဘယ် route နဲ့မှ မကိုက်တဲ့ request တွေကို 404 နဲ့ ဖြေပါတယ်။
Example: route သုံးခုပါတဲ့ server ကို fetch နဲ့ စမ်းခြင်း
Server က HTML home page၊ JSON status endpoint နဲ့ 404 fallback ကို ပေးပါတယ်။ Browser ဖွင့်စရာ မလိုအောင် listen callback ထဲမှာ Node 22 ရဲ့ built-in fetch() နဲ့ request သုံးခု ပို့ပြီး status၊ Content-Type နဲ့ body ကို print ထုတ်ကာ server ကို ပိတ်ပါတယ်။ Server ပိတ်သွားတော့ process က ကိုယ်တိုင် ထွက်သွားပါတယ်။
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('<h1>Home Page</h1>');
} else if (req.method === 'GET' && req.url === '/api/status') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, uptime: 'fine' }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Not found: ${req.method} ${req.url}`);
}
});
// Port 0 = "any free port"; then talk to the server with fetch
server.listen(0, async () => {
const { port } = server.address();
for (const path of ['/', '/api/status', '/missing']) {
const res = await fetch(`http://localhost:${port}${path}`);
const type = res.headers.get('content-type');
console.log(`${path} -> ${res.status} [${type}] ${await res.text()}`);
}
server.close(() => console.log('server closed'));
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- The handler
const server = http.createServer((req, res) => {ဒီ arrow function က request တစ်ခုဝင်လာတိုင်း ခေါ်ခံရပါတယ်။ Example မှာ request သုံးခု ပို့လို့ သုံးကြိမ် run ပါတယ်။
- Routing
} else if (req.method === 'GET' && req.url === '/api/status') {Method နဲ့ URL နှစ်ခုလုံးကို စစ်ပါတယ်။ POST /api/status ဆိုရင် ဒီ branch နဲ့ မကိုက်ဘဲ 404 ရပါမယ်။
- Status + headers
res.writeHead(200, { 'Content-Type': 'application/json' });Status code နဲ့ header တွေကို body မပို့ခင် တစ်ခါတည်း သတ်မှတ်ပါတယ်။ JSON body က string ဖြစ်ရလို့ နောက် line မှာ JSON.stringify() သုံးပါတယ်။
- Fallback
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });else branch ရှိနေလို့ ဘယ် URL ဖြစ်ဖြစ် အဖြေ အမြဲ ရပါတယ်၊ client က လည်နေပြီး မစောင့်ရတော့ပါဘူး။
- Port 0 and fetch
const { port } = server.address();OS ရွေးပေးလိုက်တဲ့ port ကို ဖတ်ပြီး fetch URL ဆောက်ပါတယ်။ Port နံပါတ်က run တိုင်း ပြောင်းနိုင်လို့ print မထုတ်ပါဘူး၊ ဒါကြောင့် output က အမြဲ အတူတူပါ။
- Shutting down
server.close(() => console.log('server closed'));Request အသစ် လက်ခံတာ ရပ်ပြီး ဖွင့်ထားတဲ့ connection တွေ ပိတ်သွားမှ callback ကို ခေါ်ပါတယ်။ ဒါမှ Node process က ကိုယ်တိုင် ထွက်သွားပါတယ်။
/ -> 200 [text/html; charset=utf-8] <h1>Home Page</h1>
/api/status -> 200 [application/json] {"ok":true,"uptime":"fine"}
/missing -> 404 [text/plain; charset=utf-8] Not found: GET /missing
server closedRequest body ကို ဖတ်ခြင်း
POST request က JSON လို data ပို့လာရင် req.body ဆိုတာ မရှိပါဘူး — req ကိုယ်တိုင်က readable stream ဖြစ်ပြီး data က chunk လေးတွေ ခွဲပြီး ရောက်လာပါတယ်။ for await နဲ့ chunk တွေကို စုပြီး ပေါင်းကာ JSON.parse() လုပ်ရပါတယ်။ အောက်က helper ကို Readable.from() နဲ့ ဖန်တီးထားတဲ့ stream အတု နဲ့ စမ်းထားလို့ server မလိုဘဲ run လို့ ရပါတယ်။ Real server မှာ JSON မှားနေရင် 400 ပြန်ပေးဖို့ try/catch ထည့်ပါ။ Express ရဲ့ express.json() ကလည်း အတွင်းမှာ ဒီအလုပ်ကိုပဲ လုပ်ပေးတာပါ။
import { Readable } from 'node:stream';
async function readJson(req) {
const chunks = [];
for await (const chunk of req) chunks.push(Buffer.from(chunk));
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}
// A stand-in for req: the body arrives in two chunks
const fakeReq = Readable.from(['{"name":"Ay', 'e","age":21}']);
console.log(await readJson(fakeReq));လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Production app အများစုက http module ကို တိုက်ရိုက် မရေးဘဲ Express၊ Fastify လို framework တွေ သုံးကြပါတယ်။ ဒါပေမယ့် framework တိုင်းက အတွင်းမှာ http.createServer() ပဲ ခေါ်ပြီး req နဲ့ res ကို ချဲ့ထားတာပါ။ "headers already sent" error၊ timeout ဖြစ်နေတဲ့ request၊ မှားနေတဲ့ Content-Type လို bug တွေကို debug လုပ်တဲ့အခါ ဒီ lesson က အလွှာကို နားလည်ထားမှ အကြောင်းရင်းကို မြန်မြန် ရှာတွေ့ပါတယ်။
Raw http server ကို တိုက်ရိုက် ရေးတဲ့ နေရာတွေလည်း ရှိပါတယ်။ Kubernetes က ခေါ်တဲ့ /healthz endpoint တစ်ခုတည်း လိုတဲ့ worker process၊ GitHub webhook လက်ခံတဲ့ script သေးသေးလေး၊ dependency မထည့်ချင်တဲ့ CLI tool ရဲ့ local preview server တွေမှာ ဒီ module တစ်ခုတည်းနဲ့ လုံလောက်ပါတယ်။ Integration test တွေကလည်း ဒီ lesson လိုပဲ port 0 ပေါ်မှာ server ဖွင့်၊ fetch နဲ့ ခေါ်၊ ပြီးရင် close() လုပ်ပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Branch တစ်ခုမှာ res.end() မေ့တာ
res.write() က body ကို ပို့ပေမယ့် response ကို မပိတ်ပါဘူး။ end() မခေါ်ရင် browser က loading လုပ်နေပြီး server ဘက်မှာ error message တစ်ခုမှ မပေါ်ပါဘူး။ if/else ကွင်းဆက်ရဲ့ branch တိုင်း end() နဲ့ ဆုံးမဆုံး စစ်ပါ။
2. Body ပို့ပြီးမှ header သတ်မှတ်တာ
res.end() ဒါမှမဟုတ် ပထမ res.write() ခေါ်ပြီးတာနဲ့ header တွေ network ပေါ် ထွက်သွားပြီ ဖြစ်လို့ နောက်က setHeader() က "ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client" ကို throw လုပ်ပါတယ်။ Header နဲ့ status ကို handler ရဲ့ အစောပိုင်းမှာ သတ်မှတ်ပါ။
3. Query string ပါတဲ့ URL ကို === နဲ့ နှိုင်းယှဉ်တာ
/search?q=node ကို ခေါ်ရင် req.url === '/search' က false ဖြစ်လို့ 404 ရပါတယ်။ new URL(req.url, 'http://localhost').pathname နဲ့ path ကို ယှဉ်ပြီး searchParams နဲ့ query ကို ဖတ်ပါ။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- JSON ပို့တာကို sendJson() လို helper တစ်ခုထဲ စုထားပါ၊ ဒါမှ Content-Type မေ့တာ၊ stringify မေ့တာ မဖြစ်တော့ပါဘူး။
- Route မတွေ့ရင် 404၊ method မှားရင် 405 + Allow header ဆိုပြီး ခွဲပြန်ပါ၊ client တွေ debug လုပ်ရ လွယ်ပါတယ်။
- Handler ထဲမှာ ကြာတဲ့ synchronous အလုပ် (loop ကြီး၊ readFileSync) မလုပ်ပါနဲ့၊ တခြား request အားလုံး စောင့်နေရပါလိမ့်မယ်။
Mini challenge
Mini challenge: JSON greeting API
http module တစ်ခုတည်းနဲ့ /api/greet endpoint ပါတဲ့ JSON API သေးသေးလေး ရေးပြီး fetch နဲ့ request လေးခု ပို့ကာ စမ်းပါ။
- sendJson(res, status, data) helper က status၊ Content-Type: application/json နဲ့ body ကို ပို့ရမယ်
- GET /api/greet?name=Aye က 200 နဲ့ {"message":"Hello, Aye!"} ပြန်ရမယ်၊ name မပါရင် "stranger" ကို သုံးရမယ်
- POST /api/greet က 405 နဲ့ Allow: GET header ပြန်ရမယ်
- တခြား URL တွေ 404 JSON ရပြီး စမ်းပြီးရင် server ကို ပိတ်ရမယ်
import http from 'node:http';
function sendJson(res, status, data, extraHeaders = {}) {
// TODO: writeHead with Content-Type application/json + extraHeaders
// TODO: end with the JSON string
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
// TODO: /api/greet + GET -> 200 { message: 'Hello, <name>!' }
// TODO: /api/greet + other method -> 405 with an Allow header
// TODO: anything else -> 404 { error: 'Not found' }
});
server.listen(0, async () => {
// TODO: fetch the four cases, print "<status> <body>", then close
});ရလဒ်: ရရမယ့် output: 200 {"message":"Hello, Aye!"} 200 {"message":"Hello, stranger!"} 405 {"error":"Use GET"} allow=GET 404 {"error":"Not found"}
အရိပ်အမြွက် ကြည့်ရန်
url.pathname ကို route အတွက်၊ url.searchParams.get('name') ?? 'stranger' ကို နာမည်အတွက် သုံးပါ။ fetch မှာ method: 'POST' ထည့်ရင် POST request ဖြစ်ပါတယ်၊ res.headers.get('allow') နဲ့ Allow header ကို ဖတ်ပါ။
အဖြေ ကြည့်ရန်
import http from 'node:http';
function sendJson(res, status, data, extraHeaders = {}) {
res.writeHead(status, { 'Content-Type': 'application/json', ...extraHeaders });
res.end(JSON.stringify(data));
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/api/greet') {
if (req.method !== 'GET') {
return sendJson(res, 405, { error: 'Use GET' }, { Allow: 'GET' });
}
const name = url.searchParams.get('name') ?? 'stranger';
return sendJson(res, 200, { message: `Hello, ${name}!` });
}
sendJson(res, 404, { error: 'Not found' });
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const cases = [
['GET', '/api/greet?name=Aye'],
['GET', '/api/greet'],
['POST', '/api/greet'],
['GET', '/nope'],
];
for (const [method, path] of cases) {
const res = await fetch(base + path, { method });
const allow = res.headers.get('allow');
console.log(res.status, await res.text(), allow ? `allow=${allow}` : '');
}
server.close();
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- http.createServer(handler) က request တစ်ခုစီအတွက် handler(req, res) ကို ခေါ်တယ်။
- req.method နဲ့ req.url (path + query) ကိုကြည့်ပြီး route ခွဲကာ ဘယ်ဟာနဲ့မှ မကိုက်ရင် 404 ပြန်ပါ။
- writeHead() နဲ့ status + Content-Type ကို အရင် သတ်မှတ်ပြီး end() ကို လမ်းကြောင်းတိုင်း တစ်ကြိမ်တည်း ခေါ်ပါ။
- Port 0 ပေါ်မှာ listen၊ fetch နဲ့ စမ်း၊ server.close() နဲ့ ပိတ် — ဒါက test တွေရဲ့ ပုံမှန် recipe ပါ။
HTTP — Node.js