ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
GET က data ကို မေးတာဖြစ်ပြီး POST ကတော့ data အသစ်ကို ပေးပို့တာပါ။ Sign-up form ကို submit လုပ်တဲ့အခါ browser က POST /api/users ကို ခေါ်ပြီး { "name": "Hla Hla" } လို JSON ကို request body ထဲ ထည့်ပို့ပါတယ်။
Server ဘက်က form စစ်တဲ့ ရုံးဝန်ထမ်းလို လုပ်ရပါတယ်။ Form ပြည့်စုံလား၊ ဖြည့်ထားတာ မှန်လား စစ်ပြီး မှားရင် "ဘယ် field မှားတယ်" ဆိုတာ စာရင်းနဲ့ ပြန်ပေးပါတယ်။ မှန်ရင်တော့ file နံပါတ်အသစ် (id) ပေးပြီး သိမ်းကာ "ဖန်တီးပြီးပါပြီ၊ ဒီနေရာမှာ ရှာလို့ရပါတယ်" လို့ ပြန်ပြောပါတယ်။
Problem → Why → Solution
ပြဿနာ: body ကို ယုံပြီး id ကို length နဲ့ ပေးတာ
အောက်က draft က happy path မှာ အလုပ်လုပ်ပါတယ်။ ဒါပေမယ့် Content-Type header မပါတဲ့ request ရောက်လာရင် Express 5 မှာ req.body က undefined ဖြစ်လို့ req.body.name က TypeError ပစ်ပြီး client က 500 ရပါတယ်။ { "name": 42 } ပို့ရင် name.trim() က crash ဖြစ်ပါတယ်။
အဆိုးဆုံးက id ပါ။ User 2 ကို ဖျက်ပြီးတဲ့အခါ users.length + 1 က 3 ဖြစ်သွားပြီး user 3 ရှိပြီးသားဖြစ်လို့ id တူတဲ့ user နှစ်ယောက် ဖြစ်သွားပါတယ်။ ဒါ့အပြင် ဘာမှမစစ်ဘဲ req.body တစ်ခုလုံးကို push လုပ်လို့ client က { "role": "admin" } ကိုပါ ထည့်ပို့ပြီး ကိုယ့်ကိုယ်ကို admin လုပ်နိုင်ပါတယ်။
app.post('/api/users', (req, res) => {
const name = req.body.name.trim(); // crashes: no body, or name is 42
const newUser = { ...req.body, id: users.length + 1, name }; // copies any field
users.push(newUser);
res.json(newUser); // 200, not 201
});ဘာကြောင့် ဒါက အန္တရာယ်များလဲ
Request body ဆိုတာ internet ပေါ်က ဘယ်သူမဆို ပို့လို့ရတဲ့ data ပါ။ Frontend form က name ကို required လုပ်ထားလည်း curl ဒါမှမဟုတ် Postman နဲ့ form ကို ကျော်ပြီး တိုက်ရိုက် ပို့လို့ ရပါတယ်။ ဒါကြောင့် server ဘက်မှာ field တိုင်းကို ကိုယ်တိုင် စစ်ရပြီး ကိုယ်လက်ခံချင်တဲ့ field တွေကိုပဲ ရွေးယူရပါတယ်။
Core concept: parse၊ validate၊ create၊ 201
POST route တစ်ခုမှာ request တစ်ခုက အဆင့်လေးဆင့်ကို ဖြတ်သွားပါတယ်။ ပထမအဆင့်ကို middleware က လုပ်ပေးပြီး ကျန်တာတွေကို ကိုယ့် handler က လုပ်ပါတယ်။
၁။ express.json() က body ကို parse လုပ်တယ်
Content-Type: application/json ပါတဲ့ request ဆိုရင် body text ကို JSON.parse လုပ်ပြီး req.body ထဲ ထည့်ပါတယ်။ Header မကိုက်ရင် Express 5 မှာ req.body က undefined ဖြစ်နေပါတယ် (Express 4 မှာတော့ {} ပါ)။ ဒါကြောင့် req.body ?? {} လို့ ရေးပါ။ JSON ပုံစံမှားရင် middleware က type: 'entity.parse.failed' ပါတဲ့ 400 error ကို error handler ဆီ ပို့ပါတယ်။
၂။ Field တိုင်းကို စစ်ပြီး error တွေ စုပါ
Type (typeof name === 'string')၊ အရှည်၊ ခွင့်ပြုထားတဲ့ value (ROLES) တွေကို စစ်ပါ။ ပထမ error တွေ့တာနဲ့ မရပ်ဘဲ error အားလုံးကို array ထဲ စုပြီး တစ်ခါတည်း ပြန်ပေးရင် user က form ကို တစ်ကြိမ်တည်းနဲ့ ပြင်နိုင်ပါတယ်။
၃။ ကိုယ်တိုင် object အသစ် တည်ဆောက်ပါ
req.body ကို တိုက်ရိုက် push မလုပ်ဘဲ validate လုပ်ပြီးသား name နဲ့ role ကိုပဲ ယူပါ။ id ကို server က nextId++ နဲ့ ပေးပါတယ်။ Counter က ဘယ်တော့မှ နောက်မဆုတ်လို့ user ဖျက်ပြီးရင်တောင် id ထပ်မနေပါဘူး။
၄။ 201 နဲ့ Location ပြန်ပါ
201 Created က "resource အသစ် ဖြစ်သွားပြီ" ဆိုတဲ့ အဓိပ္ပာယ်ပါ။ Location header က အသစ်ရဲ့ URL (/api/users/4) ကို ပြောပြပြီး body ထဲမှာ id ပါတဲ့ user အပြည့်အစုံ ပြန်ပါတယ်။ ဒါမှ client က GET ထပ်ခေါ်စရာ မလိုပါဘူး။
| ဖြစ်ရပ် | Status | Body |
|---|---|---|
| Valid body | 201 + Location | { data: user } |
| Field မှား/မပါ | 400 | { error, details: [...] } |
| JSON ပုံစံမှား | 400 | { error } |
400 လား 422 လား
API တချို့က JSON ပုံစံမှန်ပေမယ့် value မှားတဲ့ request ကို 422 Unprocessable Content နဲ့ ဖြေပြီး ပုံစံကိုက ကျိုးနေတဲ့ JSON ကိုမှ 400 သုံးပါတယ်။ HTTP standard က နှစ်ခုလုံးကို သတ်မှတ်ထားလို့ နှစ်မျိုးလုံး မှန်ပါတယ်။ အရေးကြီးတာက တစ်မျိုးကို ရွေးပြီး endpoint တိုင်းမှာ အတူတူ သုံးဖို့ပါ။ ဒီ course မှာ ရိုးရှင်းအောင် validation error အားလုံးကို 400 နဲ့ ပြန်ပါတယ်။
- express.json() က body ကို object ပြောင်း
- Field တိုင်းကို စစ်ပြီး error စု
- စစ်ပြီးသား field နဲ့ object အသစ် ဆောက်
- 201 + Location + { data } ပြန်
Client ပို့တဲ့ object ကို ဘယ်တော့မှ တိုက်ရိုက် မသိမ်းပါနဲ့။ ကိုယ်တိုင် ရွေးပြီး ဆောက်ထားတဲ့ object ကိုပဲ သိမ်းပါ။
အခြေခံ ပုံစံ
app.use(express.json());
app.post('/api/items', (req, res) => {
const { errors, value } = validate(req.body ?? {});
if (errors.length) return res.status(400).json({ error: 'msg', details: errors });
const item = { id: nextId++, ...value };
items.push(item);
res.status(201).location(`/api/items/${item.id}`).json({ data: item });
});Validate function က error list နဲ့ သန့်စင်ပြီးသား value ကို ပြန်ပေးပါတယ်။ Handler က အဲဒီ value ကိုပဲ သုံးပြီး item ဆောက်ပါတယ်။
Validation ပါတဲ့ POST /api/users
User သုံးယောက်ရဲ့ နောက်ကနေ ဆက်ပြီး POST route ကို ထည့်ပါတယ်။ name က space ဖြုတ်ပြီး စာလုံး 2 ကနေ 50 ထိ ဖြစ်ရပြီး role က မထည့်ရင် member ဖြစ်ပါတယ်။ Test က request လေးမျိုး ပို့ပါတယ်: မှန်တာ၊ field နှစ်ခု မှားတာ၊ body မပါတာ၊ JSON ပုံစံ ကျိုးနေတာ ဖြစ်ပါတယ်။
const express = require('express');
const app = express();
app.use(express.json());
const users = [
{ id: 1, name: 'Aung Aung', role: 'admin' },
{ id: 2, name: 'Mya Mya', role: 'member' },
{ id: 3, name: 'Zaw Zaw', role: 'member' },
];
let nextId = 4; // never reused, even after a delete
const ROLES = ['admin', 'member'];
function validateUser(body) {
const errors = [];
const name = typeof body.name === 'string' ? body.name.trim() : '';
if (name.length < 2 || name.length > 50) errors.push('name must be 2-50 characters');
const role = body.role ?? 'member';
if (!ROLES.includes(role)) errors.push(`role must be one of: ${ROLES.join(', ')}`);
return { errors, value: { name, role } };
}
app.post('/api/users', (req, res) => {
const { errors, value } = validateUser(req.body ?? {});
if (errors.length > 0) {
return res.status(400).json({ error: 'Validation failed', details: errors });
}
const user = { id: nextId++, ...value };
users.push(user);
res.status(201).location(`/api/users/${user.id}`).json({ data: user });
});
// Error handler: malformed JSON from express.json() arrives here
app.use((err, req, res, next) => {
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'Body is not valid JSON' });
}
res.status(500).json({ error: 'Internal server error' });
});
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/api/users`;
const json = { 'Content-Type': 'application/json' };
const attempts = [
['valid', { headers: json, body: JSON.stringify({ name: ' Hla Hla ' }) }],
['invalid', { headers: json, body: JSON.stringify({ name: 'K', role: 'owner' }) }],
['no body', {}],
['broken JSON', { headers: json, body: '{"name": "Ko' }],
];
for (const [label, init] of attempts) {
const res = await fetch(url, { method: 'POST', ...init });
const where = res.headers.get('location') ?? '-';
console.log(`${label}: ${res.status} location=${where}`);
console.log(` ${JSON.stringify(await res.json())}`);
}
console.log('users in memory:', users.length);
server.close();
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Safe body
const { errors, value } = validateUser(req.body ?? {});Body မပါရင် req.body က undefined ဖြစ်လို့ ?? {} နဲ့ object အလွတ် အစားထိုးပါတယ်။ ဒါကြောင့် "no body" request က crash မဖြစ်ဘဲ 400 ရပါတယ်။
- Type before trim
const name = typeof body.name === 'string' ? body.name.trim() : '';String ဟုတ်မှ trim() ခေါ်ပါတယ်။ " Hla Hla " က "Hla Hla" ဖြစ်သွားပြီး 42 လို number ကတော့ '' ဖြစ်ပြီး အရှည်စစ်တဲ့နေရာမှာ ကျပါတယ်။
- Unique ids
const user = { id: nextId++, ...value };id ကို server က ပေးပြီး value ထဲမှာ name နဲ့ role ပဲ ပါလို့ client က id ဒါမှမဟုတ် တခြား field တွေ ထည့်ပို့လို့ မရပါဘူး။
- 201 and Location
res.status(201).location(`/api/users/${user.id}`).json({ data: user });Method တွေကို ဆက်တိုက် chain လုပ်လို့ရပါတယ်။ Output မှာ location=/api/users/4 ကို မြင်ရပါတယ်။
- JSON parse errors
if (err.type === 'entity.parse.failed') {Parameter လေးခုပါတဲ့ middleware က error handler ပါ။ ဒါမရှိရင် broken JSON request အတွက် Express က HTML error page ပြန်ပါမယ်။
valid: 201 location=/api/users/4
{"data":{"id":4,"name":"Hla Hla","role":"member"}}
invalid: 400 location=-
{"error":"Validation failed","details":["name must be 2-50 characters","role must be one of: admin, member"]}
no body: 400 location=-
{"error":"Validation failed","details":["name must be 2-50 characters"]}
broken JSON: 400 location=-
{"error":"Body is not valid JSON"}
users in memory: 4POST ကို ထပ်ပို့မိရင်: idempotency
User က "Sign up" ခလုတ်ကို နှစ်ခါ နှိပ်မိတာ၊ network နှေးလို့ client library က retry လုပ်တာ ဖြစ်တတ်ပါတယ်။ POST က idempotent မဟုတ်လို့ request နှစ်ခုလုံး ရောက်ရင် user နှစ်ယောက် ဖြစ်ပါတယ်။ ဖြေရှင်းနည်း နှစ်မျိုး ရှိပါတယ်။ တစ်ခုက email လို unique ဖြစ်ရမယ့် field ကို စစ်ပြီး ရှိပြီးသားဆိုရင် 409 Conflict ပြန်တာပါ။ နောက်တစ်ခုက client က request တိုင်းမှာ Idempotency-Key header နဲ့ random key တစ်ခု ပို့ပြီး server က key တူတဲ့ request ကို ပထမအကြိမ်ရဲ့ response နဲ့ပဲ ပြန်ဖြေတာပါ။ Payment API တွေမှာ ဒုတိယနည်းကို အသုံးများပါတယ်။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ validateUser() လို function ကို လက်နဲ့ မရေးဘဲ zod လို schema library တွေနဲ့ ရေးလေ့ရှိပါတယ်။ Schema တစ်ခုက type၊ အရှည်၊ default value တွေကို တစ်နေရာတည်းမှာ ကြေညာပြီး error list ကိုလည်း အလိုလို ထုတ်ပေးပါတယ်။ သဘောတရားကတော့ ဒီ lesson နဲ့ အတူတူပါ၊ စစ်ပြီးသား value ကိုပဲ သုံးတာပါ။
Database ပါလာရင် id ကို database ကိုယ်တိုင် (auto-increment ဒါမှမဟုတ် UUID) ပေးပြီး email လို field တွေမှာ unique constraint ထားပါတယ်။ Request နှစ်ခု တစ်ပြိုင်နက် ရောက်လာရင် JavaScript ထဲက check တစ်ခုတည်းနဲ့ မလုံလောက်ပါဘူး၊ database constraint ကပဲ နောက်ဆုံး အာမခံချက် ပေးနိုင်ပါတယ်။ Frontend ကတော့ 400 response ရဲ့ details array ကို field အောက်မှာ အနီရောင် စာလုံးနဲ့ ပြပါတယ်။ Frontend ဘက်က စစ်တာလည်း အသုံးဝင်ပေမယ့် မြန်ဆန်ဖို့နဲ့ သုံးရလွယ်ဖို့သက်သက်ပါ။ Data ကို တကယ်ကာကွယ်ပေးတာက server ဘက်က စစ်ချက်ပါ။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
express.json() ကို route အောက်မှာ ထားတာ
Middleware တွေက ရေးထားတဲ့ order အတိုင်း run လို့ app.post() ပြီးမှ app.use(express.json()) ကို ထည့်ရင် route ရောက်တဲ့အချိန်မှာ body ကို parse မလုပ်ရသေးပါဘူး။ req.body က undefined ဖြစ်နေပြီး "client က name မပို့ဘူး" လို့ ထင်မှားတတ်ပါတယ်။
id ကို users.length + 1 နဲ့ ပေးတာ
Delete တစ်ခု ဖြစ်ပြီးတာနဲ့ length က ကျသွားပြီး ရှိပြီးသား id ကို ပြန်ပေးမိပါတယ်။ GET /api/users/3 က user နှစ်ယောက်ထဲက ပထမတစ်ယောက်ကိုပဲ ပြန်ပေးပြီး ဒုတိယတစ်ယောက်က ရှာလို့ မရတော့ပါဘူး။ ဘယ်တော့မှ နောက်မဆုတ်တဲ့ counter ကို သုံးပါ။
Success ကို 200 နဲ့ ပြန်တာ
200 က အလုပ်ဖြစ်တယ်လို့ပဲ ပြောပြီး 201 က resource အသစ် ဖြစ်သွားကြောင်း တိတိကျကျ ပြောပါတယ်။ API test တွေနဲ့ client code တွေက 201 ကို စစ်လေ့ရှိလို့ ပြောင်းလဲမှုက သေးပေမယ့် contract ကို ကျိုးစေပါတယ်။
Best Practices
ကောင်းမွန်တဲ့ အလေ့အကျင့်များ
- Validation logic ကို handler ထဲက ခွဲပြီး { errors, value } ပြန်ပေးတဲ့ function တစ်ခုအဖြစ် ထားပါ၊ PATCH route မှာ ပြန်သုံးလို့ရပါတယ်
- Error message တွေမှာ field နာမည်နဲ့ စည်းကမ်းကို ပြောပါ ("name must be 2-50 characters")
- Request body အရွယ်အစားကို ကန့်သတ်ပါ၊ express.json() ရဲ့ default limit က 100kb ပါ
- Role လို လုံခြုံရေးနဲ့ဆိုင်တဲ့ field ကို client ကို စိတ်ကြိုက် သတ်မှတ်ခွင့် မပေးပါနဲ့၊ admin က ပြောင်းပေးတဲ့ route သီးသန့် ထားပါ
Mini challenge
Products အတွက် POST route ရေးပါ
{ id, name, price } ပါတဲ့ products resource အတွက် POST /api/products ကို ရေးပါ။ JSON မဟုတ်တဲ့ body ကို 415 နဲ့ ငြင်းပြီး name နဲ့ price ကို စစ်ကာ အောင်မြင်ရင် 201 နဲ့ Location ပြန်ပါ။
- req.is('application/json') မဟုတ်ရင် 415 Unsupported Media Type ပြန်ပါ
- name က space မဟုတ်တဲ့ string ဖြစ်ရပါမယ်
- price က 0 ထက်ကြီးတဲ့ finite number ဖြစ်ရပါမယ် (string "1800" ကို လက်မခံပါ)
- id ကို nextId counter နဲ့ ပေးပြီး 201၊ Location နဲ့ { data } ပြန်ပါ
const express = require('express');
const app = express();
app.use(express.json());
const products = [{ id: 1, name: 'Green tea', price: 2500 }];
let nextId = 2;
app.post('/api/products', (req, res) => {
// TODO: 415 unless the request is application/json
// TODO: collect details for a bad name and a bad price; 400 if any
// TODO: build { id, name, price }, push it, answer 201 + Location
});
// TODO: listen on 0, POST a valid product, a string price and a form body,
// print status, Location and body, then close the serverရလဒ်: Mohinga က 201 နဲ့ /api/products/2၊ string price က 400၊ form body က 415 ရပြီး နောက်ဆုံးမှာ products: Green tea, Mohinga လို့ ပြပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
typeof '1800' က 'string' ဖြစ်လို့ typeof price !== 'number' စစ်ချက်က string price ကို ဖမ်းပါတယ်။ Number.isFinite() က NaN နဲ့ Infinity ကိုပါ ငြင်းပါတယ်။
အဖြေ ကြည့်ရန်
const express = require('express');
const app = express();
app.use(express.json());
const products = [{ id: 1, name: 'Green tea', price: 2500 }];
let nextId = 2;
app.post('/api/products', (req, res) => {
if (!req.is('application/json')) {
return res.status(415).json({ error: 'Send the body as application/json' });
}
const { name, price } = req.body;
const details = [];
if (typeof name !== 'string' || name.trim() === '') {
details.push('name is required');
}
if (typeof price !== 'number' || !Number.isFinite(price) || price <= 0) {
details.push('price must be a positive number');
}
if (details.length > 0) {
return res.status(400).json({ error: 'Validation failed', details });
}
const product = { id: nextId++, name: name.trim(), price };
products.push(product);
res.status(201).location(`/api/products/${product.id}`).json({ data: product });
});
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/api/products`;
const asJson = (body) => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const tries = [
asJson({ name: 'Mohinga', price: 3000 }),
asJson({ name: 'Tea leaf salad', price: '1800' }),
{ method: 'POST', body: 'name=Coffee&price=1500' },
];
for (const init of tries) {
const res = await fetch(url, init);
const location = res.headers.get('location') ?? '';
console.log(res.status, location, JSON.stringify(await res.json()));
}
console.log('products:', products.map((p) => p.name).join(', '));
server.close();
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- express.json() ကို route တွေ အပေါ်မှာ ထားပြီး Express 5 မှာ req.body undefined ဖြစ်နိုင်တာကို ?? {} နဲ့ ကာကွယ်ပါ
- Field တိုင်းကို type၊ အရှည်၊ ခွင့်ပြု value နဲ့ စစ်ပြီး error အားလုံးကို details array နဲ့ 400 ပြန်ပါ
- Client object ကို မသိမ်းဘဲ စစ်ပြီးသား field တွေနဲ့ object အသစ်ဆောက်ပြီး id ကို nextId counter နဲ့ ပေးပါ
- အောင်မြင်ရင် 201 Created၊ Location header နဲ့ { data } ပြန်ပြီး malformed JSON ကို error handler နဲ့ JSON 400 ပြောင်းပါ
Express routing — Express.js