-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathserver.js
90 lines (73 loc) · 2.31 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
const express = require('express');
const app = express();
const path = require('path');
const cors = require('cors');
const { logger } = require('./middleware/logEvents');
const errorHandler = require('./middleware/errorHandler');
const PORT = process.env.PORT || 3500;
// custom middleware logger
app.use(logger);
// Cross Origin Resource Sharing
const whitelist = ['https://www.yoursite.com', 'http://127.0.0.1:5500', 'http://localhost:3500'];
const corsOptions = {
origin: (origin, callback) => {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'));
}
},
optionsSuccessStatus: 200
}
app.use(cors(corsOptions));
// built-in middleware to handle urlencoded data
// in other words, form data:
// ‘content-type: application/x-www-form-urlencoded’
app.use(express.urlencoded({ extended: false }));
// built-in middleware for json
app.use(express.json());
//serve static files
app.use(express.static(path.join(__dirname, '/public')));
app.get('^/$|/index(.html)?', (req, res) => {
//res.sendFile('./views/index.html', { root: __dirname });
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
app.get('/new-page(.html)?', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'new-page.html'));
});
app.get('/old-page(.html)?', (req, res) => {
res.redirect(301, '/new-page.html'); //302 by default
});
// Route handlers
app.get('/hello(.html)?', (req, res, next) => {
console.log('attempted to load hello.html');
next()
}, (req, res) => {
res.send('Hello World!');
});
// chaining route handlers
const one = (req, res, next) => {
console.log('one');
next();
}
const two = (req, res, next) => {
console.log('two');
next();
}
const three = (req, res) => {
console.log('three');
res.send('Finished!');
}
app.get('/chain(.html)?', [one, two, three]);
app.all('*', (req, res) => {
res.status(404);
if (req.accepts('html')) {
res.sendFile(path.join(__dirname, 'views', '404.html'));
} else if (req.accepts('json')) {
res.json({ "error": "404 Not Found" });
} else {
res.type('txt').send("404 Not Found");
}
});
app.use(errorHandler);
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));