-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
97 lines (78 loc) · 2.35 KB
/
router.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
var fs = require('fs');
var express = require('express');
var router = express.Router();
var Student = require('./student');
router.get('/students', function (req, res) {
// fs.readFile('db.json','utf8',function(err,data){
// if(err){
// return res.status(500).send('Server error');
// }
// var students = JSON.parse(data).students; //通过文件读取的数据为字符串,要先转化为对象
// res.render('index.html',{
// fruit:[
// '苹果',
// '香蕉',
// '句子',
// '是你豪哥',
// 'hg'
// ],
// students:students
// });
// });
Student.find(function (err, students) {
if (err) {
return res.status(500).send('Server error');
}
res.render('index.html', {
fruit: [
'苹果',
'句子',
'是你豪哥',
'hg'
],
students: students
});
});
});
router.get('/students/new', function (req, res) {
res.render('new.html');
});
router.post('/students/new', function (req, res) {
// 1、获取表单数据
// 2、处理,将数据保存到db,json中
// 3、发送响应
new Student(req.body).save(function (err) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students');
})
});
router.get('/students/edit', function (req, res) {
Student.findById(req.query.id.replace(/"/g,''), function (err, student) {
if (err) {
console.log(err);
return res.status(500).send('Server error');
}
res.render('edit.html', {
student: student
})
})
});
router.post('/students/edit', function (req, res) {
Student.findByIdAndUpdate(req.body.id.replace(/"/g,''),req.body, function (err) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students');
})
});
router.get('/students/delete', function (req, res) {
Student.findByIdAndRemove(req.query.id.replace(/"/g,''), function (err) {
if (err) {
return res.status(500).send('Server err');
}
res.redirect('/students');
})
});
module.exports = router;