-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (66 loc) · 2.09 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import express from 'express'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import connectMongo from 'connect-mongo'
import cors from 'cors'
import session from 'express-session'
import routerUser from './routers/users.js'
import routerProduct from './routers/products.js'
import routerOrder from './routers/order.js'
import routerShare from './routers/share.js'
dotenv.config()
mongoose.connect(process.env.DBURL, { useNewUrlParser: true, useUnifiedTopology: true })
const app = express()
app.use(bodyParser.json())
// 跨域設定
app.use(cors({
origin (origin, callback) {
// 如果是 Postman 之類的後端, 允許
if (origin === undefined) {
callback(null, true)
} else {
if (process.env.DEV === 'true') {
// 如果是本機開發, 接受所有請求
callback(null, true)
} else if (origin.includes('github')) {
// 如果不是本機開發, 但是是從 github 過來的請求, 允許
callback(null, true)
} else {
// 如果不是本機開發, 也不是從 github 過來, 拒絕
callback(new Error('Not allowed'), false)
}
}
},
credentials: true
}))
const MongoStore = connectMongo(session)
const sessionSettings = {
secret: 'album',
store: new MongoStore({ mongooseConnection: mongoose.connection }),
cookie: {
maxAge: 1000 * 60 * 30
},
saveUninitialized: false,
rolling: true,
resave: true
}
if (process.env.DEV === 'false') {
// 如果不是本機的開發環境,允許不同網域的認證
sessionSettings.cookie.sameSite = 'none'
// 如果是不同網域的認證,一定要設定 secure
sessionSettings.cookie.secure = true
}
app.use(session(sessionSettings))
// 部署上 heroku 一定要設定
app.set('trust proxy', 1)
app.use('/users', routerUser)
app.use('/products', routerProduct)
app.use('/orders', routerOrder)
app.use('/shares', routerShare)
app.use((_, req, res, next) => {
res.status(500).send({ success: false, message: '伺服器錯誤' })
})
app.listen(process.env.PORT, () => {
console.log('server started')
})