--- tags: Node.js 直播班 - 2023 春季班 --- # 🏅 Day 16 - req.params 取得特定資料 ### 參考資源 - [Express 4.x - API 參照(req.params)](https://expressjs.com/zh-tw/api.html#req.params) - 課程影音「params - 取得指定路徑」 ## 題目(將答案寫在 HackMD 並提交至回報區) 延續 Day 15 每日任務,練習取得(GET) 特定貼文資料 請在先前每日任務的 express [專案](https://github.com/dogwantfly/express-add-post)使用 express 提供的 req.params 取得貼文 id,並使用 mongoose 尋找符合 id 的資料,最後 response 該特定貼文資料(若 id 不存在可做簡易錯誤處理) 例如:例如當 client 端輸入這個[網址](https://www.facebook.com/sfismy/posts/5281803261839276)時,可以 response 該特定貼文資料 將 routes/posts.js 中,取得單一貼文的程式碼貼至 HackMD 並提交至回報區 ## 回報流程 將答案連結貼至底下回報就算完成了喔! 解答位置請參考下圖(需打開程式碼的部分觀看) ![](https://i.imgur.com/vftL5i0.png) <!-- 解答: 範例參考(可自行優化程式碼) ```javascript router.get('/:id', async(req, res, next) => { try { const id = req.params.id; const post = await Post.find({_id: id }); if (post.length) { res.status(200).json({ status: 'success', data: { post } }); } else { res.status(400).json({ status: 'fail', message: "id 不存在" }); } } catch (err) { res.status(400).json({ status: 'fail', message: err.message }); } }) ``` --> 回報區 --- | 報數 | 組別/Discord 名字 | Codepen/HackMD/其他回饋 | |:----:|:-----------------------:|:-------------------------------------------------------------------------:| | 1 | 北 10 組 / Benson | [Github Benson - Day 16](https://github.com/ioveasdkre/HexschoolOperation/tree/main/NodejsEnterpriseClass/day40-tasks/day16/app.ts) | | 2 | 中 4 組 / jimkk159 | [HackMD - Day 16](https://hackmd.io/1FkGYUnFTYqEz_IlyKRwlw) | | 3 | 北 12 組 / Sam Lin | [GitHub - Day 16](https://github.com/samlin1122/hex-school/blob/main/daily-challenges/day16.js)| | 4 | 北 5 組 / 圈圈 | [GitHub - Day 16](https://github.com/panduola666/hexschool-node.js-homework/blob/main/day15/routes/posts.js)| | 5 | 北 1 組 / PittWu | [Blog Post - Day 16](https://pitt-wu-blog.vercel.app/docs/day16-request-params) | | 6 | 北 13 組 / Louisa | [GitHub - Day 16](https://github.com/louisa0416/NodejsEnterpriseClass/tree/master/daily-task/day16) | | 7 | 南 1 組 / hiYifang | [HackMD - Day 16](https://hackmd.io/@gPeowpvtQX2Om6AmD-s3xw/HkiSA6Jrc) |