forked from mdn/serviceworker-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
65 lines (56 loc) · 1.95 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
var express = require('express');
var bodyParser = require('body-parser');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var app = express();
app.use(bodyParser.json());
app.use(function maskIndex(req, res, next) {
// Adding this redirect to simplify caching a recipe page,
// essentially so we don't have to cache "/" and "/index.html"
// So: "recipe/index.html" -> "recipe/" , "index.html?123" -> "?123"
if (/\/(.*)\/index\.html\??(.*)$/.test(req.url)) {
return res.redirect(req.url.replace('index.html', ''));
}
return next();
});
app.use(function forceSSL(req, res, next) {
var host = req.get('Host');
var localhost = 'localhost';
if (host.substring(0, localhost.length) !== localhost) {
// https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
res.header('Strict-Transport-Security', 'max-age=15768000');
// https://github.com/rangle/force-ssl-heroku/blob/master/force-ssl-heroku.js
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect('https://' + host + req.url);
}
}
return next();
});
app.use(function corsify(req, res, next) {
// http://enable-cors.org/server_expressjs.html
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept');
next();
});
glob.sync('./*/server.js').map(function requireRecipe(file) {
var route = '/' + path.basename(path.dirname(file)) + '/';
require(file)(app, route);
});
if (!fs.existsSync('./dist')) {
throw new Error('Missing `dist` folder, execute `npm run build` first.');
}
app.use(express.static('./dist'));
var port = process.env.PORT || 3003;
var ready = new Promise(function willListen(resolve, reject) {
app.listen(port, function didListen(err) {
if (err) {
reject(err);
return;
}
console.log('app.listen on http://localhost:%d', port);
resolve();
});
});
exports.ready = ready;
exports.app = app;