1.视图层
根目录/views/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .table { border: 1px solid #eee; text-align: center; } .table td, .table th { border: 1px solid #eee; text-align: center; } </style> </head> <body> <br /> <br /> <a href="/add">增加用户</a> <br /> <br /> <table class="table"> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>操作</th> </tr> {{each list}} <tr> <td>{{$value.username}}</td> <td>{{$value.age}}</td> <td>{{$value.sex}}</td> <td> <a href="#">删除</a> <a href="#">编辑</a> </td> </tr> {{/each}} </table> </body> </html>
根目录/views/add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h2>学员增加</h2> <form action="/doAdd" method="post"> <br />用户名: <input type="text" name="username" /> <br /> <br /> 年龄: <input type="text" name="age" /> <br /> <br /> 性别: <input type="text" name="sex" /> <br /> <br /> <input type="submit" value="提交" /> </form> </body> </html>
2.控制层
app.js
// 引入模块 const Koa = require('koa'); const router = require('koa-router')(); /*引入是实例化路由 推荐*/ const render = require('koa-art-template'); const path = require('path'); const BodyParser = require('koa-bodyparser'); const DB = require('./module/db.js'); // 实例化 let app = new Koa(); // 配置post提交数据的中间件 app.use(BodyParser()); // 配置 koa-art-template 模板引擎 render(app, { root: path.join(__dirname, 'views'), // 视图的位置 extname: '.html', // 后缀名 debug: process.env.NODE_ENV !== 'production' // 是否开启调试模式 }) // 显示学员信息 router.get('/', async (ctx) => { let result = await DB.find('user', {}); await ctx.render('index', { list: result }); }) // 增加学员 router.get('/add', async (ctx) => { await ctx.render('add'); }) // 执行增加学员的操作 router.post('/doAdd', async (ctx) => { // 获取表单提交的数据 // console.log(ctx.request.body); // { name: 'aaa', age: 'aa', sex: 'a' } let data = await DB.insert('user', ctx.request.body); // console.log(data); try { if (data.result.ok) { ctx.redirect('/'); } } catch (err) { console.log(err); ctx.redirect('/add'); } }) // 编辑学员 router.get('/edit', async (ctx) => { let data = await DB.update('user', { 'username': '赵六' }, { 'username': '赵六666' }); console.log(data.result); ctx.body = '更新数据'; }) // 删除学员 router.get('/delete', async (ctx) => { let data = await DB.remove('user', { 'username': '张珊珊' }); console.log(data.result); ctx.body = '删除数据'; }) app.use(router.routes()); app.use(router.allowedMethods()); app.listen(3000);
3.效果图