koa是由express的原班人馬打造的web框架。可是相對於express,koa的性能要更高,由於koa經過使用aysnc函數,幫你丟棄回調函數,並有力的加強了錯誤處理。並且koa沒有綁定任何中間件,二十提供了一套優雅的方法,幫助你快死而愉快地編寫服務端應用程序。javascript
與express的區別css
框架 | 推薦版本 | 是否自帶中間件 | js語法 | 特性 |
express | 4.x | 是 | es5 | 回調嵌套 |
koa2 | 2.x | 否 | es7 | async/await+Promise |
koa依賴的node>v7.6.0html
npm i koa -D
要在 node < 7.6 版本的 Koa 中使用 async
方法, 咱們推薦使用 babel's require hook.java
建立hello world應用程序,在文件中建立server.js,文件內的代碼以下node
const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Hello World'; }); app.listen(3000);
在終端中啓動web
node server.js
服務啓動以後,在瀏覽器中輸入localhost:3000,就會看到頁面顯示的是hello world的字樣數據庫
由於koa自己是不帶任何中間件的,因此使用路由的話,咱們須要安裝koa的路由才行express
npm i koa-router -D
使用npm
const Koa=require('koa'); const Router=require('koa-router'); let app=new Koa(); server.listen(8080); let router=new Router(); router.get('/news', async (ctx, next)=>{ ctx.body='hello world'; await next(); }); app.use(router.routes());
啓動服務後在瀏覽器地址欄打開:localhost:3000/news後端
既然是服務端語言,作項目的時候,先後端通訊確定是少不了請求方式處理的
const koa = require('koa'); const Router = require('koa-router'); let server = new koa(); server.listen(2000, () => { console.log('port 2000 is running'); }) // 建立路由
let router = new Router(); // koa裏面習慣於用async await ,有next方法,可是很是的少用
router.get('/a', async ctx => { //至關於 express的send
ctx.body = 'aaa'; console.log(ctx.body) }) // 最後須要把路由添加到服務器上
server.use(router.routes())
post請求
post請求的話,須要使用到 koa-better-body模塊
安裝
npm i koa-better-body
咱們這裏使用文件上傳做爲例子,在文件目錄下新建一個static文件夾,而且在static文件夾裏面建一個upload文件夾
const koa=require('koa'); const body=require('koa-better-body'); const app=new koa(); app.listen(3000,()=>{ console.log('server is running...'); }) app.use(body({ uploadDir:'./static/upload' })) app.use(async ctx=>{ //文件和post數據
console.log(ctx.request.fields); ctx.body='數據提交成功啦' })
html文件中的表單使用的post請求
<!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>
<form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
<div> 用戶名:<input type="text" name="username">
</div>
<div> 密碼:<input type="password" name="password">
</div>
<div> 文件:<input type="file" name="file">
</div>
<div>
<input type="submit" value="提交">
</div>
</form>
</body>
</html>
注意點:1 . 由於這邊是文件上傳,因此用到的是post請求,entype必定要寫成multipart/form-data
2. 上傳完成後在upload文件夾裏面能看到你剛剛上傳的文件,後綴名多是不必定是你上傳的文件的後綴名,這不是上傳失敗,這是正常的後綴名是給人看的,不是給機器看的
koa傳參有兩種方式 urlencodeded 和 params兩種方式
query | params |
順序靈活 | 順序寫死 |
能夠省略 | 不能省略,不然會報not found |
不利於SEO | 利於SEO |
http://aaa.com/user?a=12&b=5 | http://aaa.com/user/12/5 |
const koa=require('koa'); const Router=require('koa-router'); const app=new koa(); const router=new Router(); app.listen(3000); router.get('/news/:id',async (ctx,next)=>{ let {id}=ctx.params ctx.body=id; }) app.use(router.routes())
const koa=require('koa'); const Router=require('koa-router'); const app=new koa(); const router=new Router(); app.listen(3000); router.get('/news/:id',async (ctx,next)=>{ let {id}=ctx.params ctx.body=id; next() })
app.use(router.routes());
Koa Context 將 node 的 request
和 response
對象封裝到單個對象中,爲編寫 Web 應用程序和 API 提供了許多有用的方法。 這些操做在 HTTP 服務器開發中頻繁使用,它們被添加到此級別而不是更高級別的框架,這將強制中間件從新實現此通用功能。
app.context至關因而ctx的原型(prototype).
經常使用:在使用數據庫的時候,能夠把數據庫的對象添加到app.context上
const koa=require('koa'); const Router=require('koa-router'); const app=new koa(); // 添加數據庫到全局
app.context.db=require('./libs/database'); // 由於全部的請求都會走這一步,因此在這邊添加錯誤處理能提升性能
app.use(async (ctx, next)=>{ try{ await next(); }catch(e){ ctx.body='錯了'; } }); const router=new Router(); router.get('/a',async ctx=>{ // ctx.db.query(`SELECT * FROM user_table`,(err,data)=>{
// if(err) return err;
// console.log(data);
// })
// console.log(query)
console.log(ctx.db); ctx.body='weqwe' }) // 全部路由都會通過這裏,因此在這邊進行錯誤處理
router.all('',async ctx=>{ try{ await next(); }catch(e){ ctx.body='沒有該路由' } }) app.use(router.routes()); app.listen(3000);
處理cookie的話,koa裏面已經封裝好了,因此不須要咱們引入中間件
前面已經說到過koa不帶任何中間件,因此要管理靜態資源的話,須要安裝koa-static
const koa=require('koa');
const Router=require('koa-router');
const static=require('koa-static');
const app=new koa();
let router=new Router();
router.get('/user',async ctx=>{
ctx.body='用戶'
})
app.use(router.routes());
app.listen(3000,()=>{
console.log('server is running....')
})
app.use(static('./static',{
maxAge:86400*1000,// 設置緩存時間
index:'1.html'// 根目錄的時候打開這個文件
}))
在項目中,由於不一樣的文件,咱們須要設置緩存的時間不同,咱們能夠進行下面的操做
const Koa = require('koa'); const Router = require('koa-router'); const static = require('koa-static'); const app = new Koa(); app.listen(3000); let router = new Router(); router.get('/user', async ctx => { ctx = '用戶' }) app.use(router.routes()); let staticRouter = new Router(); staticRouter.all(/(\.jpg|\.png|\.gif)$/i, static('./static', { maxAge: 60 * 86400 * 1000 })); staticRouter.all(/(\.css)$/i, static('./static', { maxage: 1 * 86400 * 1000 })); staticRouter.all(/(\.html|\.htm|\.shtml)$/i, static('./static', { maxage: 20 * 86400 * 1000 })); staticRouter.all('', static('./static', { maxage: 30 * 86400 * 1000 })); app.use(staticRouter.routes());
安裝koa-seesion
const koa=require('koa');
const session=require('koa-session');
const app=new koa();
app.listen(3000,()=>{
console.log('port is running...')
})
app.keys=[
'eehuehuwehwue',
'eweyweywewyqeuw',
'dhsjdhasdasjd',
'sdsadasdsa'
]
app.use(session({
maxAge:60*20*1000,// 有效期
renew:true // 自動續期
},app))
app.use(async ctx=>{
if(!ctx.session['view']){
ctx.session['view']=1;
}
ctx.session['view']++
ctx.body=`歡迎你第${ctx.session.view}次來訪`
})