1.視圖層javascript
根目錄/views/index.htmlhtml
<!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.htmljava
<!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
app.jskoa
// 引入模塊 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.效果圖async