-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
executable file
·72 lines (53 loc) · 1.93 KB
/
server.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
const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
const dotenv = require('dotenv');
dotenv.config();
const SSL_KEY_PATH = process.env.SSL_KEY_PATH;
const SSL_CERT_PATH = process.env.SSL_CERT_PATH;
if (!fs.existsSync(SSL_KEY_PATH)) {
console.error(`SSL key required!\nPlease provide the ssl key in the .env file in SSL_KEY_PATH.`);
process.exit();
}
if (!fs.existsSync(SSL_CERT_PATH)) {
console.error(`SSL certificate required!\nPlease provide the ssl certificate in the .env file in SSL_CERT_PATH.`);
process.exit();
}
const privateKey = fs.readFileSync(SSL_KEY_PATH, 'utf8');
const certificate = fs.readFileSync(SSL_CERT_PATH, 'utf8');
const credentials = {
key: privateKey,
cert: certificate
};
const app = express();
const port_http = process.env.PORT_HTTP;
const port_https = process.env.PORT_HTTPS;
// Redirect HTTP to HTTPS
app.enable('trust proxy');
app.use(function (req, res, next) {
if (req.secure) {
next(); // request was via https, so do no special handling
} else {
// request was via http, so redirect to https
const host = req.headers.host || '';
if (host.includes(':')) {
res.writeHead(301, {Location: `https://${host.replace(/:\d+/, ':'.concat(port_https))}${req.url}`});
} else {
res.writeHead(301, {Location: `https://${host}${':'.concat(port_https)}${req.url}`});
}
res.end();
}
});
app.use(express.static(__dirname + '/dist'));
app.get('/*', function (req, res) {
res.sendFile(__dirname + '/dist/index.html');
});
const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);
httpServer.listen(port_http, () => {
console.log('Dashboard with HTTP runing in PORT ' + port_http);
});
httpsServer.listen(port_https, () => {
console.log('Dashboard with HTTPS runing in PORT ' + port_https);
});