Node.js(day4) (4)

修改router.js

module.exports = function(app){ var stuUtil = require('./student.js'); //主页(直接跳到学生信息页好了) app.get('http://www.likecs.com/',(req,res) => { res.redirect(302,'/students'); }); //学生信息页 app.get('/students',(req,res) => { stuUtil.queryAll((students) => { res.render('./index.html',{ "students":students }); }); }); //增加学生信息页 app.get('http://www.likecs.com/students/add',(req,res) => { res.render('./add.html'); }); //增加学生 app.post('http://www.likecs.com/students/add',(req,res) => { var stu = req.body; stu.id = Math.floor(Math.random()*1000+1);//产生随机整数 stuUtil.add(stu); res.redirect(302,'/students'); }); //删除学生 app.get('/students/delete',(req,res) => { stuUtil.delete(parseInt(req.query.id),(flag) =>{ if(flag) res.redirect(302,'/students'); else res.send('500'); }); }); //修改学生信息页 app.get('/students/modify',(req,res) => { stuUtil.queryById(parseInt(req.query.id),(stu) => { res.render('./modify.html',{"stu":stu}); }); }); //修改学生 app.post('/students/modify',(req,res) => { req.body.id = parseInt(req.body.id); stuUtil.modify(req.body,(flag) => { if(flag) res.redirect(302,'/students'); else res.send('500'); }); }); }

效果

Node.js(day4)

5.使用express提供的路由管理

具体参考

app.js

var express = require('express'); var bodyParser = require('body-parser'); //路由 var router = require('./router.js'); var app = express(); app.listen('8080',() => { console.log('server running at 8080'); }); //配置 app.use('/public',express.static('./public')); app.engine('html',require('express-art-template')); app.use(bodyParser.urlencoded({extended:false})); app.use(bodyParser.json()); app.use(router);//挂载路由 module.exports = app;

router.js

var stuUtil = require('./student.js'); var express = require('express'); var router = express.Router(); //主页(直接跳到学生信息页好了) router.get('http://www.likecs.com/',(req,res) => { res.redirect(302,'/students'); }); //学生信息页 router.get('/students',(req,res) => { stuUtil.queryAll((students) => { res.render('./index.html',{ "students":students }); }); }); //增加学生信息页 router.get('http://www.likecs.com/students/add',(req,res) => { res.render('./add.html'); }); //增加学生 router.post('http://www.likecs.com/students/add',(req,res) => { var stu = req.body; stu.id = Math.floor(Math.random()*1000+1);//产生随机整数 stuUtil.add(stu); res.redirect(302,'/students'); }); //删除学生 router.get('/students/delete',(req,res) => { stuUtil.delete(parseInt(req.query.id),(flag) =>{ if(flag) res.redirect(302,'/students'); else res.send('500'); }); }); //修改学生信息页 router.get('/students/modify',(req,res) => { stuUtil.queryById(parseInt(req.query.id),(stu) => { res.render('./modify.html',{"stu":stu}); }); }); //修改学生 router.post('/students/modify',(req,res) => { req.body.id = parseInt(req.body.id); stuUtil.modify(req.body,(flag) => { if(flag) res.redirect(302,'/students'); else res.send('500'); }); }); module.exports = router;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzpzf.html