http module က Node.js ကို web server အဖြစ် request လက်ခံပြီး response ပြန်ပေးနိုင်စေတဲ့ built-in module ပါ။ Express.js မသုံးခင် HTTP request/response flow ကိုနားလည်ဖို့ ဒီ module က အကောင်းဆုံး foundation ဖြစ်ပါတယ်။
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
if (req.url === '/') {
res.statusCode = 200;
res.end('<h1>Home Page</h1><p>Welcome to Node.js.</p>');
} else if (req.url === '/about') {
res.statusCode = 200;
res.end('<h1>About Page</h1><p>This page is served by Node.js.</p>');
} else {
res.statusCode = 404;
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(5000, () => {
console.log('Server is listening on http://localhost:5000');
});req.url က user ဝင်လာတဲ့ path ကိုပြပါတယ်။ / ဆို home page, /about ဆို about page ပြန်ပေးပါတယ်။ မကိုက်ရင် 404 status code နဲ့ not found ပြန်ပေးပါတယ်။
Server is listening on http://localhost:5000 Browser: http://localhost:5000/about About PageInfo
Status code ကိုမှန်မှန်ပြန်ပေးတာက API/web server quality အတွက်အရေးကြီးပါတယ်။ Success ဆို 200, created ဆို 201, not found ဆို 404, server error ဆို 500 စသဖြင့်သုံးပါတယ်။