Thuta Learning
ရှာဖွေရန်
IntermediateWeb Developmentbeginner

HTTP Module

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

http module က Node.js ကို web server အဖြစ် request လက်ခံပြီး response ပြန်ပေးနိုင်စေတဲ့ built-in module ပါ။ Express.js မသုံးခင် HTTP request/response flow ကိုနားလည်ဖို့ ဒီ module က အကောင်းဆုံး foundation ဖြစ်ပါတယ်။

javascript
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 ပြန်ပေးပါတယ်။

You should see
Server is listening on http://localhost:5000 Browser: http://localhost:5000/about About Page

Info

Status code ကိုမှန်မှန်ပြန်ပေးတာက API/web server quality အတွက်အရေးကြီးပါတယ်။ Success ဆို 200, created ဆို 201, not found ဆို 404, server error ဆို 500 စသဖြင့်သုံးပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • res.end() ကိုမခေါ်မိရင် request ကပြီးဆုံးမသွားဘဲ browser loading ဖြစ်နေနိုင်ပါတယ်။

လေ့ကျင့်ခန်း

Express.js က ဒီ HTTP concept အပေါ်မှာပိုလွယ်အောင်တည်ဆောက်ထားတာပါ။ ဒီ lesson နားလည်ရင် Express routing ကိုပိုမြန်မြန်နားလည်ပါမယ်။

You'll know it worked when: