Koa 是由 Express 原班人馬打造的超輕量服務(wù)端框架
與 Express 相比,除了自由度更高,可以自行引入中間件之外,更重要的是使用了 ES6 + async,從而避免了回調(diào)地獄
不過也是因?yàn)榇a升級(jí),所以 Koa2 需要 v7.60 以上的 node.js 環(huán)境
手動(dòng)創(chuàng)建一個(gè)項(xiàng)目目錄,然后快速生成一個(gè) package.json 文件
npm init -y
安裝 koa //當(dāng)前版本 2.4.1
npm install koa -S
然后創(chuàng)建一個(gè) app.js
// app.js const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Wise Wrong'; }); app.listen(3000);
最后在 package.json 中添加啟動(dòng)指令
一個(gè)最基礎(chǔ)的 koa 應(yīng)用就這樣完成了
可以執(zhí)行 npm start 并在瀏覽器訪問 http://localhost:3000/ 查看效果
如果覺得手動(dòng)創(chuàng)建項(xiàng)目太過繁瑣,可以使用腳手架 koa-generato 來生成項(xiàng)目
npm install koa-generator -g
koa2 project_name
然后在項(xiàng)目下 npm install 安裝依賴,npm start 啟動(dòng)項(xiàng)目
如果是剛接觸 koa,建議先看完這篇博客,再使用腳手架工具,這樣能更好的理解各個(gè)依賴包的作用
上面 app.js 中有一個(gè) ctx,這是一個(gè) Koa 提供的 Context 對(duì)象,封裝了 request 和 response
每一次 HTTP Request 都會(huì)創(chuàng)建一個(gè) Context 對(duì)象
我們可以通過 Context.request.path 來獲取用戶請(qǐng)求的路徑,然后通過 Context.response.body 給用戶發(fā)送內(nèi)容
Koa 默認(rèn)的返回類型是 text/plain,如果要返回一個(gè) html 文件(或者一個(gè)模塊文件),就需要修改 Context.response.type
另外,Context.response 可以簡(jiǎn)寫,比如 Context.response.type 簡(jiǎn)寫為 Context.type,Context.response.body 簡(jiǎn)寫為 Context.type
在項(xiàng)目下創(chuàng)建一個(gè)存放 html 文件的目錄 views,并在該目錄下創(chuàng)建一個(gè) index.html,然后修改 app.js
// app.js// 原生路由 const Koa = require('koa'); const fs = require('fs'); const app = new Koa(); app.use(async (ctx, next) => { if (ctx.request.path === '/index') { ctx.type = 'text/html'; ctx.body = fs.createReadStream('./views/index.html'); } else { await next(); } }); app.listen(3000);
然后在瀏覽器中訪問 http://localhost:3000/index 就能看到 index.html 頁面,而訪問別的地址則是 not found
這樣處理 url 顯得特別笨拙,所以我們需要引入路由中間件 koa-router
npm install koa-router -S
需要注意的是,在導(dǎo)入 koa-router 的時(shí)候,需要在末尾加一個(gè)括號(hào):
const router = require('koa-router')();
相當(dāng)于:
const koaRouter = require('koa-router'); const router = koaRouter();
創(chuàng)建一個(gè) routes 目錄,用來存放路由文件,并在目錄下創(chuàng)建 index.js
// routes/index.js const fs = require('fs'); const router = require('koa-router')() router.get('/index', async (ctx, next) => { ctx.type = 'text/html'; ctx.body = fs.createReadStream('./views/index.html'); }); module.exports = router
這里還可以使用 prefix 方法,為文件中的所有接口添加一個(gè) baseUrl
// router.prefix('/about')
修改 app.js
// app.js const Koa = require('koa'); const app = new Koa(); const index = require('./routes/index') app.use(index.routes(), index.allowedMethods()) app.listen(3000);
上面的 allowedMethods 用于校驗(yàn)請(qǐng)求的方法,如果用 post 請(qǐng)求訪問 get 接口,就會(huì)直接返回失敗
另外,還可以在 url 中添加變量,然后通過 Context.params.name 訪問
router.get('/about/:name', async (ctx, next) => { ctx.body = `I am ${ctx.params.name}!`; });
在上面的 index.html 中,如果需要引入 css 等靜態(tài)資源,就需要用到 koa-static
npm install koa-static -S
創(chuàng)建一個(gè)目錄 public 用來存放靜態(tài)資源
然后在 app.js 中添加以下代碼
const static = require('koa-static'); // 將 public 目錄設(shè)置為靜態(tài)資源目錄 const main = static(__dirname + '/public'); app.use(main);
事實(shí)上,這三行代碼還可以優(yōu)化
app.use(require('koa-static')(__dirname + '/public'));
然后就能在 index.html 中引入對(duì)應(yīng)的文件了
上面的路由是使用 fs 模塊直接讀取 html 文件
開發(fā)的時(shí)候更推薦使用 koa-views 中間件來渲染頁面
npm install koa-views -S
在 app.js 中將 views 目錄設(shè)定為模版目錄
const views = require('koa-views') app.use(views(__dirname + '/views'));
然后在路由文件中,就能使用 render 方法了
// routes/index.js const router = require('koa-router')() router.get('/index', async (ctx, next) => { await ctx.render('index'); }); module.exports = router
以上是直接渲染 html 文件的方法,如果要引入模板引擎,可以添加 extension 字段來設(shè)定模版類型
app.use(views(__dirname + '/views', { extension: 'pug' // 以 pug 模版為例 }))
如果將 Express 看作 webstorm,那么 Koa 就是 sublime
當(dāng) Express 流行的時(shí)候,其冗雜的依賴項(xiàng)被很多開發(fā)者所詬病
所以 Express 團(tuán)隊(duì)將 Express 拆卸得只剩下最基本的骨架,讓開發(fā)者自行組裝,這就是 Koa
正如文中所說,從零開始太過繁瑣,可以使用腳手架 koa-generato 來快速開發(fā)
不過我更推薦,在熟悉了 Koa 之后,搭一個(gè)適合自己項(xiàng)目的腳手架
上面是我整理給大家的,希望今后會(huì)對(duì)大家有幫助。
相關(guān)文章:
express與koa的使用對(duì)比(詳細(xì)教程)
在vue中首次使用stylus安裝方法(詳細(xì)教程)
Vue框架中有關(guān)goods組件開發(fā)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com