-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
50 lines (43 loc) · 1.4 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const express = require('express')
const exphbs = require('express-handlebars').engine
// 載入種子資料
const restaurants = require('./restaurant.json').results
// 判斷資料的個數,用於限定動態路由的區間
const restaurantsCount = restaurants.length
const port = 3000
const app = express()
app.engine('handlebars', exphbs({ defaultLayout: 'main' }))
app.set('view engine', 'handlebars')
app.set('views', './views')
// 靜態資料統一放在 public
app.use(express.static('public'))
// 首頁
app.get('/', (req, res) => {
res.render('index', { restaurants })
})
// 各餐廳的介紹
app.get(`/restaurants/:id([1-${restaurantsCount}])`, (req, res) => {
const selectedIndex = Number(req.params.id) - 1
const selectedRestaurant = restaurants[selectedIndex]
res.render('show', { selectedRestaurant })
})
// 收尋的路由
app.get('/search', (req, res, next) => {
const keyword = req.query.keyword.toLowerCase()
const searchedRestaurant = restaurants.filter((restaurant) => {
const { name, category } = restaurant
return (name + category).toLowerCase().includes(keyword)
})
if (searchedRestaurant.length) {
res.render('index', { restaurants: searchedRestaurant, keyword })
} else {
next()
}
})
// 查無資料時的路由
app.get('*', (req, res) => {
res.render('notFound')
})
app.listen(port, () => {
console.log('this server is listening on http://localhost:3000')
})