/
app.js
75 lines (70 loc) · 2.14 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
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
const express = require('express');
const cors = require('cors');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const fs = require('fs');
const https = require('https');
const SSLKey = fs.readFileSync('./cert/server.key');
const SSLCert = fs.readFileSync('./cert/server.pem');
const extensions = require('./extensions');
const app = express();
dotenv.config();
app.use(cors({
origin: [
// 'http://localhost:8080',
'http://test.blog.zachary.tw',
'http://blog.zachary.tw',
],
methods: ['GET', 'POST'],
credentials: true // enable set cookie
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.set('trust proxy', 1);
app.use(session({
secret: 'zachary-techblog',
name: 'csid',
resave: true,
saveUninitialized: false,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'none'
}
}));
fs.readdirSync('./routes').forEach(fileName => {
fileName = fileName.replace('.js', '');
app.use('/' + fileName, require('./routes/' + fileName + '.js'));
});
// 若執行環境為local, 則開啟https連線並使用自簽金鑰
if (process.env.SERVER_ENV === 'local') {
// https連線預設PORT為443, http為80
// const port = process.env.SERVER_PORT || 443;
// const server = https.createServer({
// key: SSLKey,
// cert: SSLCert
// }, app);
// server.listen(port, function() {
// const host = server.address().address;
// const port = server.address().port;
// console.log(`Server start listening https://${host}:${port}/`);
// });
const port = process.env.SERVER_PORT || 80;
const server = app.listen(port, function () {
const host = server.address().address;
const port = server.address().port;
console.log(`Server start listening http://${host}:${port}/`);
});
} else {
const port = process.env.SERVER_PORT || 80;
const server = app.listen(port, function () {
const host = server.address().address;
const port = server.address().port;
console.log(`Server start listening http://${host}:${port}/`);
});
}