-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
71 lines (60 loc) · 1.57 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
var path = require('path');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var siteRouter = require('./routes/site');
var userRouter = require('./routes/user');
var editRouter = require('./routes/edit');
var app = express();
// body-parser
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
// Session
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'secret_key',
cookie: {
maxAge: 24 * 60 * 60 * 1000
}
}));
// Setting
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static('public'));
app.use((req, res, next) => {
res.locals.query = req.query;
res.locals.url = req.originalUrl;
next();
});
// If login
app.use((req, res, next) => {
res.locals.user = req.session.user;
if (req.session.user) {
if (/^\/user\/(login|signup)/g.test(req.originalUrl)) {
return res.redirect('/');
}
} else {
if (/^\/edit/g.test(req.originalUrl)) {
return res.redirect('/');
}
}
next();
});
// Alert message
app.use((req, res, next) => {
if (req.session.message) {
res.locals.message = req.session.message;
req.session.message = null;
}
next();
});
app.use('/', siteRouter);
app.use('/user', userRouter);
app.use('/edit', editRouter);
app.get('*', (req, res) => {
res.status(404).render('error', {title: 'Not Found (#404)'});
});
app.listen(3000, () => console.log('Web app listening on port 3000!'));