-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.js
261 lines (230 loc) · 6.85 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
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
const express = require('express'),
path = require('path'),
fs = require('fs'),
http = require('http')
https = require('https'),
cookieparser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
uuid = require('node-uuid'),
xss = require('xss'),
{resolve, join} = path,
app = express(),
port = process.env.NODE_PORT || 3000,
isHttps = process.env.IS_SSL || false,
ImageStorage = join(__dirname,'/database/img-storage'),
{
PublishNew,
PublishFeedBack,
getAllDataes,
sortDataes,
delData,
delFeedBack,
voteUp
} = require('./model/model.js')
if (!isHttps) {
http.createServer(app).listen(port,()=>console.log(`正在监听${port}端口`));
} else {
let options = {
key: fs.readFileSync(resolve(__dirname, './certificates/key.pem')),
cert: fs.readFileSync(resolve(__dirname, './certificates/cert.pem'))
}
https.createServer(options, app).listen(port,()=>console.log(`正在监听${port}端口`));
}
app.use(session({
url: `localhost:${port}`,
name: 'kuolun_Id',
secret: 'KuoLun secret',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60 * 1000 * 60 * 24 * 7 }
}))
app.use(bodyParser.json());
app.use(bodyParser.text({limit: '50mb'}))
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieparser());
app.use(express.static(join(__dirname, '/test')));
app.use(express.static(join(__dirname, '/dist')));
app.use(express.static(join(__dirname, '/public')));
app.use(express.static(join(__dirname, '/database')));
// 分页页码限制 前后端都需要统一
const PaginationLimit = 6;
const Ok = (res, meg) => {
res
.status(200)
.end(meg)
}
app.get('/', (req, res) => {
res.sendFile(`${__dirname + '/test/test.html'}`);
})
// 用户访问时候,查询Session是否已经登录,如果登录,修改View层登录状态
app.post('/checkLogin', (req, res) => {
let key = decodeURIComponent(req.cookies['kuolun_Id']),
value = req.session[key] || {};
res.json(JSON.stringify(value));
})
// 登出时 清除用户信息
app.post('/delSession', (req, res) => {
let key = decodeURIComponent(req.cookies['kuolun_Id']);
delete req.session[key]
Ok(res,'中断session 对话成功');
})
// 登录的时候设置用户信息在Session中
app.post('/setSession', (req, res) => {
let key = decodeURIComponent(req.cookies['kuolun_Id']);
req.session[key] = req.body;
Ok(res,'建立session 对话成功');
})
app.post('/resDataes', (req, res) => {
let { whichpage, SortState } = req.body;
getAllDataes((result) => {
let box = []
box = sortDataes(result, SortState);
let mul = whichpage * PaginationLimit;
res.json(JSON.stringify({
allLen: box.length,
Data: box.slice(mul, mul + PaginationLimit)
}))
},(err) => {
console.log(err);
res
.status(500)
.end('数据库查询出现错误');
})
})
app.post('/delData', (req, res) => {
let {
whichpage,
SortState,
index,
ParentIndex
} = req.body;
if (ParentIndex == -1) {
delData(index, (result) => {
Ok(res, '删除成功');
}, (err) => {
res
.status(500)
.end('删除失败')
})
} else {
delFeedBack( index, ParentIndex, (result) => {
// result -> { ok: 1, nModified: 1, n: 1 }
Ok(res,'删除回复成功');
},() => {
res
.status(500)
.end('删除回复失败')
})
}
})
// 存储被上传的图片
app.post('/upLoadImage', (req, res) => {
let reg = /^(\d+)data\:image\/(png|jpg|webp|gif|jpeg|svg)\;base64\,(.+)/,
match = req.body.match(reg),
order = match[1],
type = match[2],
content = match[3];
const saveImage = () => {
let id = uuid.v1({
node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
clockseq: 0x1234,
msecs: new Date().getTime(),
nsecs: 5678
}),
url = `${ImageStorage}/${id}.${type}`
let stream = fs.createWriteStream(url)
stream.end(content, 'base64')
stream.on('error', (err) => {
console.log(err);
res.status(500).end('存储失败')
})
stream.on('finish', () => {
res.status(200).end(JSON.stringify({order,url: `/img-storage/${id}.${type}`}));
})
}
if(reg.test(req.body)) {
fs.exists(ImageStorage, (isexist) => {
if(isexist) {
saveImage();
} else {
fs.mkdir(ImageStorage, (err) => {
if(err) {
console.log(err);
res.status(500).end('存储失败')
} else {
saveImage();
}
})
}
})
} else {
res.status(400).end('数据类型非图片')
}
})
app.get('/img-storage', (req,res) => {
res.status(403).end('403')
})
// 图片服务器
// app.get('/img-storage/:imagename', (req, res) => {
// let key = req.params['imagename'],
// url = join(req.originalUrl,'/database/img-storage/',key);
// fs.exists(url, (isexist) => {
// if(!isexist) {
// res.redirect('*')
// } else {
// res.sendFile(url);
// }
// })
// })
app.post('/saveData', (req,res) => {
let oData = req.body.newContent,
FBIndex = req.body.FBIndex
// 防xss
oData.publish_content = xss(oData.publish_content);
// 如果没有FBIndex 说明是普通评论
if (FBIndex != -1) {
PublishFeedBack(FBIndex,
(result) => {
result.FeedBack.push(oData);
result
.save()
.then(() => {
Ok(res, '存储成功');
})
.catch(() => {
res
.status(500)
.end('存储失败')
})
})
} else {
oData.index = parseInt(oData.index)
PublishNew(oData,
() => {
Ok(res, '存储成功');
},(err) => {
console.error(err);
res
.status(500)
.end('存储失败')
})
}
})
app.post('/VoteUpSomeItem', (req, res) => {
let {
index
} = req.body
voteUp(parseInt(index), () => {
Ok(res, '点赞成功')
}, () => {
res
.status(500)
.end('点赞失败')
})
})
app.get('*', (req, res) => {
res.end('404!!!!');
})