这篇文档主要介绍了利用express实现增删改查的效果,主要学习开发过程中的模块化处理。
1. 起步
2. 路由设计
| 请求方法 |
请求路径 |
get参数 |
post 参数 |
备注 |
| GET |
/students |
|
|
渲染首页 |
| GET |
/students/new |
|
|
渲染添加学生页面 |
| POST |
/students/new |
|
name, age, gender, hobbies |
处理添加学生请求 |
| GET |
/students/edit |
id |
|
渲染编辑页面 |
| POST |
/students/edit |
|
id, name, age, gender, hobbies |
处理编辑页面 |
| GET |
/students/delete |
id |
|
处理删除请求 |
3. 将入口文件app.js和路由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
|
const express = require('express');
const router = express.Router();
router.get('/students', function (req, res){
});
router.get('/students/new', function (req, res){
});
router.post('/students/new', function (req, res){
});
router.get('/students/edit', function (req, res){
});
router.post('/students/edit', function (req, res){
});
router.get('/students/delete', function (req, res){
});
module.exports = router;
|
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
|
const express = require('express'); const app = express(); const router = require('./router.js');
app.engine('html', require('express-art-template'));
app.use('/node_modules/', express.static('./node_modules')); app.use('/public', express.static('./public'));
app.use(router);
app.listen(3000, function (){ console.log('express is running ....'); });
|
4. 设计操作数据的API文件模块
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
|
const dbPath = './db.json'; const fs = require('fs');
exports.find = function (callback){ fs.readFile(dbPath, 'utf8', function (err, data){ if(err){ callback(err) } callback(null, JSON.parse(data).students) }) };
exports.save = function (){
};
exports.update = function (){
};
exports.delete = function (){
};
|
5. 步骤整理
- 处理模板
- 配置开放静态资源
- 配置模板引擎
- 简单路由:/students渲染页面
- 路由设计
- 提取路由模块
- 封装students.js处理文件数据
- 先写好student.js的文件结构
- 实现具体功能