-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
63 lines (49 loc) · 1.87 KB
/
Copy pathapp.js
File metadata and controls
63 lines (49 loc) · 1.87 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 載入 express 並建構應用程式伺服器
const express = require('express')
const session = require('express-session')
const exphbs = require('express-handlebars')
const bodyParser = require('body-parser')
const methodOverride = require('method-override')
const flash = require('connect-flash')
// 如果在 Heroku 環境則使用 process.env.PORT
// 否則為本地環境,使用 3000
const PORT = process.env.PORT || 3000
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
const routes = require('./routes') // 引用路由器
const usePassport = require('./config/passport')
require('./config/mongoose')
const app = express()
app.engine('hbs', exphbs({ defaultLayout: 'main', extname: '.hbs' }))
app.set('view engine', 'hbs')
app.use(session({
// session 用來驗證 session id 的字串
secret: 'LoginInfo',
// 每一次與使用者互動後,強制把 session 更新到 session store 裡
resave: false,
// 強制將未初始化的 session 存回 session store
saveUninitialized: true
}))
// setting static files
app.use(express.static('public'))
// 用 app.use 規定每一筆請求都需要透過 body-parser 進行前置處理
app.use(bodyParser.urlencoded({ extended: true }))
// 設定每一筆請求都會透過 methodOverride 進行前置處理
app.use(methodOverride('_method'))
// 呼叫 Passport 函式並傳入 app,這條要寫在路由之前
usePassport(app)
app.use(flash()) // 掛載套件
app.use((req, res, next) => {
res.locals.isAuthenticated = req.isAuthenticated()
res.locals.user = req.user
res.locals.success_msg = req.flash('success_msg') // 設定 success_msg 訊息
res.locals.warning_msg = req.flash('warning_msg') // 設定 warning_msg 訊息
next()
})
// 將 request 導入路由器
app.use(routes)
// 設定 port 3000
app.listen(PORT, () => {
console.log(`App is running on http://localhost:${PORT}`)
})