---
tags: Node.js 直播班 - 2023 春季班
---
# 🏅 Day 14 - req.query 篩選網址參數
除了先前使用 `req.params` 取得動態路由外,也可在 url 帶入相關資訊,再使用 `req.query` 取出網址列的參數
例如:網址列為 `https://example.com/over/there?name=ferrett&color=purple`,其中 ? 用來分隔後面帶入的參數 `name=ferret` 及 `color=purple`,多個參數之間也會使用 & 分隔
當使用者造訪此網址時, express 可以使用 req.query 取出網址列的這些參數
```javascript
app.get('https://example.com/over/there?name=ferrett&color=purple)', function(req, res) {
console.log(req.query)
...
});
// req.query
{
name: 'ferret',
color: 'purple'
}
```
使用 `req.query.name` 或 `req.query.color` 就可以取出需要的資訊做相關處理
req.query 常見的應用是搜尋關鍵字,當使用者輸入關鍵字後,會將關鍵字帶到網址列中,伺服器接收到,再藉由 req.query 取出,尋找資料庫中符合其關鍵字的資料,並回傳至客戶端
```
GET 'https://example.com/search?q=apple' // 通常會以 q 表示搜尋關鍵字
```
```javascript
app.get('/search', function(req, res) {
const q = req.query.q
const results = await Data.find(q); // 使用 mongoose 搜尋資料庫中符合 req.query.q 的資料
res.status(200).json({
status: 'success',
results: results.length,
data: {
results
}
});
});
```
### 參考資源
- [Express - req.query](https://expressjs.com/zh-tw/api.html#req.query)
- 課程影音「query - 取得網址參數」
## 題目(將答案寫在 HackMD 並提交至回報區)
請在 express 專案中,將以下 url 中的參數使用 req.query 取出,並回傳取出的參數(可自行建立 express 專案,先在 app.js 練習即可)
```javascript
'http://localhost:3000/products?category=music&page=1' // 在 POSTMAN 發出 GET 請求
app.get('/products', function(req, res) {
// 取出參數
/* 請在此填寫答案*/
res.status(200).json({
status: 'success',
data: {
/* 請在此填寫答案*/
}
});
});
```
## 回報流程
將答案連結貼至底下回報就算完成了喔!
解答位置請參考下圖(需打開程式碼的部分觀看)

<!-- 解答:
```javascript
app.get('/products', function(req, res) {
// 取出參數
const category = req.query.category;
const page = req.query.page;
res.status(200).json({
status: 'success',
data: {
category,
page,
}
});
});
```
-->
回報區
---
| 報數 | 組別/Discord 名字 | Codepen/HackMD/其他回饋 |
|:----:|:-----------------------:|:-------------------------------------------------------------------------:|
| 1 | 北 10 組 / Benson | [Github Benson - Day 14](https://github.com/ioveasdkre/HexschoolOperation/tree/main/NodejsEnterpriseClass/day40-tasks/day14/app.ts) |
| 2 | 中 4 組 / jimkk159 | [HackMD - Day 14](https://hackmd.io/84OQw26bT0i09CQhPTAIEA) |
| 3 | 北 1 組 / PittWu | [Blog Post - Day 14](https://pitt-wu-blog.vercel.app/docs/day14-request-query) |
| 4 | 北 12 組 / Sam Lin | [GitHub - Day 14](https://github.com/samlin1122/hex-school/blob/main/daily-challenges/day14.js)|
| 5 | 北 5 組 / 圈圈 | [HackMD - Day 14](https://hackmd.io/@j6ccRYgTTEiVcfMfmAELcw/S1fwSNe-h)|
| 6 | 中 3 組 / Wendy | [Notion - Day 14](https://jewel-cellar-80e.notion.site/Day-14-req-query-c5368e467901472a9288274b2bb5e525)|
| 7 | 北 13 組 / Louisa | [GitHub - Day 14](https://github.com/louisa0416/NodejsEnterpriseClass/tree/master/daily-task/day14) |
| 8 | 北 13 組 / sasha | [HackMD - Day 14](https://hackmd.io/@sashaye/Sk5lCXubh)|
| 9 | 南 1 組 / hiYifang | [HackMD - Day 14](https://hackmd.io/@gPeowpvtQX2Om6AmD-s3xw/HkiSA6Jrc)|
| 10 | 北 16 組 / 啊培培 | [GitHub - Day 14](https://github.com/LABIBI-LG/Courses/blob/main/hexschool/nodeJS/Live_Course/Daily_Tasks/day14/app.js)|