app.js
1.99 KB
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
/**
* 应用入口
* @author xuqi<qi.xu@yoho.cn>
* @date: 2016/3/28
*/
var express = require('express'),
path = require('path'),
hbs = require('hbs'),
bodyParser = require('body-parser');
var logger = require('morgan'),
favicon = require('serve-favicon'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
connectRedis = require('connect-redis');
var config = require('./config');
var app = express(),
RedisStore = connectRedis(session);
// 根据不同配置获取不同配置
if (app.get('env') === 'development') {
config = Object.assign(config, require('./config.dev'));
}
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);
app.set('views', path.join(__dirname, 'views/action'));
app.set('view engine', 'hbs');
hbs.registerPartials(path.join(__dirname, '/views/partials'));
app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// session 配置
app.use(session({
name: 'yoho-activity',
resave: true,
saveUninitialized: true,
httpOnly: true,
store: new RedisStore(config.sessionRedis),
secret: config.sessionSecret
}));
// 向模板注入变量
app.use(function(req, res, next) {
// TODO: 优化
res.locals.devEnv = app.get('env') === 'development';
next();
});
// 加载路由
app.use('/', require('./router'));
// 未知路由转入 404
app.use(function(req, res) {
var err = new Error('Not Found');
err.status = 404;
res.status(404).send(err);
});
// 捕获全局错误, 开发环境返回错误详情
app.use(function(err, req, res) {
if (app.get('env') === 'development') {
console.log(err);
} else {
err = {};
}
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
module.exports = app;