-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
112 lines (100 loc) · 2.29 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var express = require("express");
const nocache = require("nocache");
const {
expressCspHeader,
NONCE,
SELF,
EVAL,
INLINE,
} = require("express-csp-header");
const fs = require("fs");
const ejs = require("ejs");
const path = require("path");
const http = require("http");
var app = express();
app.set("view engine", "ejs");
const allowedExt = [
".js",
".ico",
".css",
".png",
".jpg",
".woff2",
".woff",
".ttf",
".svg",
];
app.use(nocache());
app.use(
expressCspHeader({
directives: {
"font-src": [SELF, "fonts.gstatic.com"],
"script-src": [SELF, "cdnjs.cloudflare.com"],
"style-src": [
SELF,
NONCE,
"fonts.googleapis.com",
"cdnjs.cloudflare.com",
],
},
// Add "reportOnly: true" for just console logs without CSP content suppression.
// reportOnly: true,
})
);
var ui = path.join(__dirname, "dist");
app.use("/", express.static(ui));
app.use("/", express.static(path.join(ui, "assets")));
app.use("/", express.static(path.join(ui, "assets", "img")));
const tokens = {};
const prefixes = [
"main",
"polyfills",
"runtime",
"scripts",
"styles",
"vendor",
];
fs.readdir("dist", (err, files) => {
prefixes.forEach((prefix) => {
const file = files.find((val) => val.startsWith(prefix));
tokens[prefix] = file
? prefix === "styles"
? `<link rel="stylesheet" href="${file}">`
: `<script src="${file}" defer></script>`
: "";
});
});
app.get("/", (req, res) => {
ejs.renderFile(
path.join(__dirname, "views", "index.ejs"),
{ nonce: req.nonce, ...tokens },
(err, result) => {
if (err) {
console.log("Error rendering index:", err);
} else {
res.send(result);
}
}
);
});
app.all("*", function (req, res) {
if (allowedExt.filter((ext) => req.url.indexOf(ext) > 0).length > 0) {
res.sendFile(path.resolve(`dist/${req.url}`));
}
});
var port = getPort();
http
.createServer(app)
.listen(port, () => console.log(`Server is running on port ${port}...`));
function getPort() {
// get port from app.json; otherwise default to 8080
const appJson = require("./app.json");
return (
(appJson &&
appJson.apps &&
appJson.apps[0] &&
appJson.apps[0].server &&
appJson.apps[0].server.port) ||
8080
);
}