Node練習 設計路由 取得指定路徑

還記得我們一開始,輸入 http://localhost:3000/
網頁會出現對應的內容(如下語法)
這是因為路由指到/,而出現相對應的內容

1
2
3
app.get('/', function(req, res) {
res.send('hello express :D')
})

若這邊我們輸入 http://localhost:3000/apple
因為抓不到對應的路由,於是回應我們

1
Cannot GET /apple

讓我們開始動手做 ~

現在我們來設計一些路由,這邊以會員頁面來當範例

  • 會員
    • 個人資料(user-profile)
    • 帳密修改(user-account)
    • 我的最愛(user-favorite)
1
2
3
app.get('/user/profile', function(req, res) {
res.send('user profile page')
})
1
2
3
app.get('/user/account', function(req, res) {
res.send('user account page')
})
1
2
3
app.get('/user/favorite', function(req, res) {
res.send('user favorite page')
})

現在我們有三個路由,依序在網址上輸入來測試
http://localhost:3000/user/profile
http://localhost:3000/user/account
http://localhost:3000/user/favorite
就會得到相對應的內容

But 當我們需要動態取得路徑時,我們該如何得到呢?

這邊會使用 params 取得路徑

1
2
3
4
5
6
app.get('/user/:name', (req, res) => {
let {name} = req.params;

console.log(name)
res.send(`${name} page`)
})

這次我們在網址上輸入
http://localhost:3000/user/xxxxxx
查看終端機,會發現印出 xxxxxx

若想要增加一些判斷,可以簡單寫成

1
2
3
4
5
6
7
8
9
app.get('/user/:name', (req, res) => {
let name = req.params;

if(name !== 'Mary') {
res.send('404 :(')
} else {
res.send('Hello Mary :)')
}
})

我們輸入
http://localhost:3000/user/Mary
出現 Hello Mary :)
http://localhost:3000/user/Andy
出現 404 :(

大家可以觀察其他網站路由設計,設計起來也會更加清楚喔~