-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
100 lines (86 loc) · 2.58 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
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
/**
* Created by slipkinem on 2016/11/20.
*/
/**
* 注意:中间件的加载顺序很重要。如上面设置静态文件目录的中间件应该放到 routes(app) 之前加载,
* 这样静态文件的请求就不会落到业务逻辑的路由里;flash 中间件应该放到 session 中间件之后加载,
* 因为 flash 是基于 session 的。
*/
'use strict';
var path = require('path'),
express = require('express'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
flash = require('connect-flash'),
config = require('config-lite'),
routes = require('./routes'),
pkg = require('./package.json'),
winston = require('winston'),
expressWinston = require('express-winston');
var app = express();
//设置模版目录
app.set('views',path.join(__dirname,'views'));
//ejs
app.set('view engine','ejs');
//静态文件目录
app.use(express.static(path.join(__dirname,'public')));
//session 中间件
app.use(session({
name: config.session.key, //设置cookie中保存session ID 的字段
secret: config.session.secret, //通过设置secret来计算hash存在cookie中,让产生的signecCookie 防止篡改
cookie: {
maxAge:config.session.maxAge //设置cookie时效
},
store: new MongoStore({ //存session到mongodb
url:config.mongodb
})
}));
//flash 中间层
app.use(flash());
//处理表单和文件上传
app.use(require('express-formidable')({
uploadDir:path.join(__dirname,'public/img'),
keepExtensions: true
}));
// 设置模板全局常量
app.locals.blog = {
title:pkg.name,
description:pkg.description
};
// 添加模板必须的三个变量
app.use((req,res,next) => {
res.locals.user = req.session.user;
res.locals.success = req.flash('success').toString();
res.locals.error = req.flash('error').toString();
next();
});
//正常请求的日志
app.use(expressWinston.logger({
transports: [
new (winston.transports.Console)({
json: true,
colorize: true
}),
new winston.transports.File({
filename: 'logs/success.log'
})
]
}));
//路由
routes(app);
//错误请求的日志
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
}),
new winston.transports.File({
filename: 'logs/error.log'
})
]
}));
// 监听端口,启动程序
app.listen(config.port, function () {
console.log(`${pkg.name} listening on port ${config.port}`);
});