-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
48 lines (37 loc) · 1.27 KB
/
Copy pathapp.js
File metadata and controls
48 lines (37 loc) · 1.27 KB
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
const express = require('express')
const { engine } = require('express-handlebars')
const app = express()
const port = 3000
//載入restaurant.json
const restaurants = require('./public/jsons/restaurant.json').results
//V(view)負責畫面的呈現
app.engine('.hbs', engine({extname : '.hbs'}))
app.set('view engine', '.hbs')
app.set('views', './views')
//M(model)負責與資料集溝通(取得了restaurant.json裡面的資料)
app.use(express.static('public'))
//C 架構的中間人(先處理)
app.get('/', (req, res) => {
res.redirect('/restaurant')
})
app.get('/restaurant',(req,res)=>{
const keyword = req.query.keyword?.trim() ;
const matchedRestaurant = keyword ?
restaurants.filter(restaurant => {
return restaurant.name.toLowerCase().includes(keyword.toLowerCase()) || restaurant.category.includes(keyword)
}
)
: restaurants ;
if (matchedRestaurant.length===0){
res.render('empty',{keyword})
}else
res.render('index',{restaurants:matchedRestaurant,keyword})
})
app.get('/restaurant/:id', (req, res) => {
const id = Number(req.params.id)
const restaurant = restaurants.find((res) => res.id === id)
res.render('detail' ,{restaurant})
})
app.listen(port, () => {
console.log(`express sever is running on http://localhost:${port}`)
})