const router = require('koa-router')()html
ctx:封裝了request 和 response變量mysql
next: 傳入將要處理的下一個異步函數git
由async標記的函數稱爲異步函數,在異步函數中,能夠用await調用另外一個異步函數,這兩個關鍵字將在ES7中引入。github
${ctx.request.url}
輸出 請求的url 地址 ctx.url至關於ctx.request.url,ctx.type至關於ctx.response.typesql
處理路由器的操做分爲:views、 string、 json、 處理get請求、 處理post請求數據庫
router.get('/', async (ctx, next) => { await ctx.render('index', { title: 'Hello Koa 2!' }) })
router.get('/string',async (ctx, next) =>{ ctx.response.body = `<h1>welcome, hello</h1>`; })
router.get('/json', async (ctx, next) => { ctx.body = { title: 'koa2 json' } })
var name = ctx.params.name;json
router.get('/info/:name', async (ctx, next) => { var name = ctx.params.name; ctx.response.body = `<h1>Hello, ${name}!</h1>`; })
var name = ctx.request.body.name || '';數組
須要引入 koa-bodyparser 中間件, 建立 info.pug 用於處理表單cookie
extends layout block content h1= title form(action="/signin" method="post") p= '用戶名:' input(type="text" name="name" value="koa") p= '密碼:' input(type="password" name="password" value="koa") p input(type="submit" value="提交")
router.get('/info', async (ctx, next) => { await ctx.render('info',{ title: '用戶信息' }); }) // 處理post請求 router.post('/signin', async (ctx,next) => { var name = ctx.request.body.name || ''; var password = ctx.request.body.password || ''; if(name === 'koa' && password === 'koa') { ctx.response.body = `<h1>welcome, ${name}</h1>`; }else{ ctx.response.body = `<h1>Login faild!</h1> <p><a href="/">Login</a></p> ` } })
適用於 koa 的模板引擎選擇很是多,好比 jade、ejs、nunjucks、handlebars 、xtemplate 等。session
Nunjucks是Mozilla開發的一個純JavaScript編寫的模板引擎 koa-nunjucks-2^3.0.2
https://mozilla.github.io/nun...
const koaNunjucks = require('koa-nunjucks-2') app.use(koaNunjucks({ ext: 'html', path: path.join(__dirname, 'views'), nunjucksConfig: { trimBlocks: true, noCache: false // 開發環境下 } }));
// 模塊 {% extends 'base.html' %} {% block body %} <div>No body</div> {% endblock %} // 循環 {% for msg in data %} <p>{{ msg }}</p> {% endfor %} {% if hungry %} I am hungry {% elif tired %} I am tired {% else %} I am good! {% endif %}
koa提供了從上下文直接讀取、寫入cookie的方法:
// 處理cookie router.get('/cookie', async (ctx,next) => { const options = { domain:'127.0.0.1', path:'/', maxAge: 10 * 60 * 1000, // cookie有效時長 expires: new Date('2019-02-02'), // cookie失效時間 httpOnly: false, // 是否只用於http請求中獲取 overwrite: false // 是否容許重寫 } ctx.cookies.set('id','test cookie',options) ctx.response.body = `<h1>cookies, ${ctx.cookies.get('id')}</h1>`; // 輸出cookie值 })
將session存放在MySQL數據庫中 koa-session-minimal、koa-mysql-session "koa-session-minimal":"^3.0.4","koa-mysql-session":"^0.0.2"
const session = require('koa-session-minimal') const MysqlSession = require('koa-mysql-session') // 配置存儲session let store = new MysqlSession({ user: 'root', password: '', database: 'test', host: '127.0.0.1', }) let cookie = { maxAge: '', // cookie有效時長 expires: '', // cookie失效時間 path: '', // 寫cookie所在的路徑 domain: '', // 寫cookie所在的域名 httpOnly: '', // 是否只用於http請求中獲取 overwrite: '', // 是否容許重寫 secure: '', sameSite: '', signed: '', } app.use(session({ key: 'SESSION_ID', store: store, cookie: cookie }))
// 處理session router.get('/session', async (ctx,next) => { ctx.session = { user_id: Math.random().toString(36).substr(2), count: 0 } ctx.response.body = `<h1>session, ${ctx.session.user_id}, ${ctx.session.count}</h1>`; // 輸出cookie值 })
安裝 mysql "mysql":"^2.15.0"
用戶增、刪、改、查
// 查詢 async function queryAll(){ let sql = usersMapping.queryAll; let UsersList = await dbUtils(sql); return UsersList; } // 新增 async function insertUser(username,password,realname){ let sql = usersMapping.insertUser; var values = [username,password,realname]; // 數組 let result = await dbUtils(sql,values); if ( Array.isArray(result) && result.length > 0 ) { result = result[0] } else { result = null } return result } // 修改 async function queryById(id){ let sql = usersMapping.queryById; let result = await dbUtils(sql,id); if ( Array.isArray(result) && result.length > 0 ) { result = result[0] } else { result = null } return result } async function updateUser(id,username,password,realname){ // 從session中取 id let sql = usersMapping.updateUser; var values = [username,password,realname,id]; // 數組 let result = await dbUtils(sql,values); if ( Array.isArray(result) && result.length > 0 ) { result = result[0] } else { result = null } return result } // 刪除 async function deleteById(id){ let sql = usersMapping.deleteById; let flag = await dbUtils(sql,id); return flag; }
github: