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

GET Single Item

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

List အားလုံးမလိုဘဲ item တစ်ခုတည်းလိုတဲ့အခါ GET single item route သုံးပါတယ်။ Express route parameter :id ကိုသုံးပြီး URL ထဲက ID ကိုဖတ်နိုင်ပါတယ်။

javascript
// Add this route after the users array
app.get('/api/users/:id', (req, res) => {
  const id = Number(req.params.id);
  const user = users.find((item) => item.id === id);

  if (!user) {
    return res.status(404).json({
      message: 'User not found'
    });
  }

  res.json(user);
});

req.params.id က URL ထဲက ID ကို string အနေနဲ့ပေးပါတယ်။ ဒါကြောင့် Number() နဲ့ number ပြောင်းပြီး users.find() နဲ့ကိုက်တဲ့ user ကိုရှာပါတယ်။ မတွေ့ရင် 404 response ပြန်ပေးပါတယ်။

You should see
GET /api/users/2 { "id": 2, "name": "Mya Mya" } GET /api/users/99 { "message": "User not found" }

Info

return res.status(...) လို့ရေးထားတာက error response ပြန်ပြီးနောက် code ဆက်မ run အောင်တားတာပါ။

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

  • req.params.id က string ဖြစ်တာကိုမေ့ပြီး number ID နဲ့ strict compare လုပ်ရင် user မတွေ့နိုင်ပါ။ Number() သို့ parseInt() နဲ့ပြောင်းပါ။

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

User profile detail page, product detail page, order detail page, article detail page တွေမှာ ဒီ pattern ကိုသုံးပါတယ်။

You'll know it worked when:

GET Single Item | Thuta Learning