-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
127 lines (92 loc) · 3.46 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
* 应用程序的启动文件
* */
// 加载express模块
var express = require('express');
// 加载模板
var swig = require('swig');
// 加载数据库模块
var mongoose = require('mongoose');
// 加载body-parser,用来处理post提交过来的数据
var bodyParser = require('body-parser')
// 加载cookies模块
var Cookies = require('cookies')
// 创建app应用 => NodeJS Http.createServe();
var app = express();
var User = require('./models/User');
// 设置静态文件托管
// 当用户访问的url以/public开始,那么直接返回对应__dirname + '/public'下的文件
app.use('/public', express.static(__dirname + '/public'));
// 配置应用模板
// 定义当前应用所使用的模板引擎
// 第一个参数:模板引擎的名称,同时也是末班文件的后缀,第二个参数表示用于解析处理模板内容的方法
app.engine('html', swig.renderFile);
// 设置模板文件存放的目录,第一个参数views, 第二个参数是目录
app.set('views', './views');
// 注册所使用的模板引擎,第一个参数必须是 view engine,第二个参数和app.engine这个方法中定义的模板引擎的名称(第一个参数)是一致的
app.set('view engine', 'html');
// 开发过程中,需要取消模板缓存
swig.setDefaults({cache: false});
// bodyparser设置
app.use( bodyParser.urlencoded({extended: true}) );
// cookies设置
app.use( function(req, res, next) {
req.cookies = new Cookies(req, res);
// 解析登录用户的cookies信息
req.userInfo = {};
if (req.cookies.get('userInfo')) {
try {
req.userInfo = JSON.parse(req.cookies.get('userInfo'));
// 获取当前用户的类型,是否是管理员
User.findById(req.userInfo._id).then(function(userInfo) {
req.userInfo.isAdmin = Boolean(userInfo.isAdmin);
next();
})
} catch (e) {
next();
}
} else {
next();
}
} );
/*
* 首页
* req:request对象
* res: response对象
* Next:函数
* */
// app.get('/', function(req, res, next) {
// // res.send('<h1>Hello Word</h1>')
//
// /*
// * 读取views目录下的指定文件,解析并返回给客户端
// * 第一个参数:表模板的文件,相对于views目录 views/index.html
// * 第二个参数:传递给模板使用的数据
// * */
// res.render('index');
// })
// app.get('/main.css', function(req, res, next) {
// res.setHeader('content-type', 'text/css');
// res.send('body {background: red;}');
// })
/*
* 根据不同的功能划分模块
* */
app.use('/admin', require('./routers/admin'));
app.use('/api', require('./routers/api'));
app.use('/', require('./routers/main'));
// 连接数据库
mongoose.connect('mongodb://localhost:27018/blog', function(err) {
if (err) {
console.log('数据库连接失败');
} else {
console.log('数据库连接成功');
// 监听http请求
app.listen(8081);
}
});
// 用户发送http请求 -> url -> 解析路由 -> 找到匹配的规则 -> 执行指定绑定函数,返回对应内容至用户
/*
* 项目分为静态文件、动态文件
* /public -> 静态 -> 直接读取指定目录下的文件,返回给用户 -> 动态 -> 处理业务逻辑,加载模板,解析模板 -> 返回数据给用户
* */