koa2的中間件功能及應(yīng)用示例
最近因?yàn)殚_發(fā)一個自己的博客網(wǎng)站,學(xué)習(xí)了koa2的搭建,寫了一些自己認(rèn)為比較重要或需要知道的koa2中間件作用和使用場景。
koa-router
路由中間件
下載
npm i koa-router
使用
普通使用方法
需要注意的是引入的koa-router是一個方法,引入后需要執(zhí)行這個方法。
const Koa = require('koa'); const app = new Koa(); const router = require('koa-router')(); // 配置路由url // 默認(rèn)url router.get('/', async (ctx, next) => { ctx.body = 'Hello World'; }); // 自定義url router.get('/hello/:name', async (ctx, next) => { var name = ctx.params.name; ctx.response.body = \`<h1>Hello, ${name}!</h1>\`; }); // 注冊路由 app.use(router.routes(), router.allowedMethods());
也可以按需引入并注冊路由,可注冊多個路由。
不同請求下接收的參數(shù)獲取
router.get
通過ctx.query獲取參數(shù)
router.post
通過ctx.request.body獲取參數(shù)
動態(tài)路由 router.get('/:id', func)
通過ctx.params獲取參數(shù)
遍歷注冊router
首先引入nodejs中的fs模塊,使用fs的readdirSync方法獲取到指定目錄的所有文件名,遍歷引入路由模塊并注冊。
const fs = require('fs');
// fs.readdirSync 獲取指定目錄下的所有文件名稱,遍歷引入路由模塊并注冊 fs.readdirSync('./routes').forEach(route=> { let api = require(\`./routes/${route}\`); app.use(api.routes(), api.allowedMethods()); });
koa-router中的其它api
router.prefix(prefix) 添加url前綴
設(shè)置已經(jīng)初始化的路由器實(shí)例的路徑前綴
router.prefix('/user'); router.post('/login', function(ctx, next) { ... }); // 實(shí)際路徑 /user/login
router.use(url|[url1,url2,...], (ctx, next) => {...}) 路由中間件
使用場景:我們通常需要通過驗(yàn)證用戶和用戶權(quán)限來判定用戶是否能使用該接口,如果在每個接口都寫一次驗(yàn)證非常麻煩且不好維護(hù)。這時我們就需要路由中間件先進(jìn)行驗(yàn)證,再執(zhí)行下面操作。
router.use的第一個參數(shù)為一個路徑或者由多個需要使用中間件的路徑組成的數(shù)組(需要注意的是,如果路由設(shè)置了url前綴,需要在設(shè)置前綴后注冊中間件,參數(shù)中的url不需要設(shè)置前綴)。
router.use的第二個參數(shù)為函數(shù),函數(shù)傳遞ctx和next兩個參數(shù),可通過ctx進(jìn)行權(quán)限驗(yàn)證后,判斷是否執(zhí)行next調(diào)用接口。這里特別需要注意的是函數(shù)使用next的時候需要添加await,如果不添加,在調(diào)用接口前,接口就會返回結(jié)果,前臺則無法獲取到數(shù)據(jù)。
// this is wrong app.use(function (ctx, next) { ctx.set("Access-Control-Allow-Origin", "\*"); next(); }); // this is right app.use(async function (ctx, next) { ctx.set("Access-Control-Allow-Origin", "\*"); await next(); });
koa-bodyparser處理post請求
處理post請求時,我們會遇到一個問題,無論是node的request對象還是koa的request對象,都沒辦法解析request的body,我們就需要下載并引入一個解析body的中間件koa-bodyparser,koa-bodyparser的具體配置詳見下面的說明,這里我們直接放入使用方式。
// 引入路由文件 const index = require('./routes/index.js'); const user = require('./routes/user.js'); // 引入解析request.body的中間件 const bodyparser = require('koa-bodyparser'); // 注冊bodyparser,需要注意,bodyparser的注冊一定要在router路由注冊之前 app.use(bodyparser({ enableTypes:\['json', 'form', 'text'\] })); ... // 注冊routes app.use(index.routes(), index.allowedMethods()); app.use(user.routes(), user.allowedMethods());
koa-bodyparser
如上所述,koa-bodyparser用于解析request.body,因?yàn)閚ode和koa的request無法解析body。
下載
npm i koa-bodyparser
使用
const bodyparser = require('koa-bodyparser');
在注冊運(yùn)行時,bodyparser方法中可傳入對象,作相應(yīng)配置。
- enableTypes:解析器只在配置了enableTypes時解析請求類型,默認(rèn)是['json', 'form']。
- encoding:請求編碼,默認(rèn)是utf-8。
- formLimit:urlencoded body的imit如果主體最終大于此限制,則返回一個413錯誤代碼。默認(rèn)是56 kb。
- jsonLimit:json主體的限制。默認(rèn)是1 mb。
- textLimit:文本主體的限制。默認(rèn)是1 mb。
- strict:當(dāng)設(shè)置為true時,JSON解析器將只接受數(shù)組和對象。默認(rèn)是正確的。參見正文中的嚴(yán)格模式。在嚴(yán)格模式下,ctx.request。body總是一個對象(或數(shù)組),這避免了很多類型判斷。但文本正文總是返回字符串類型。
- detectJSON:自定義json請求檢測函數(shù)。默認(rèn)為null。
app.use(bodyparser({ detectJSON: function (ctx) { return /\\.json$/i.test(ctx.path); } }));
- extendTypes:支持?jǐn)U展類型
app.use(bodyparser({ extendTypes: { json: \['application/x-javascript'\] // 解析application/x-javascript 類型 作為JSON字符串 } }));
- onerror:支持自定義錯誤句柄,如果koa-bodyparser拋出一個錯誤,您可以自定義響應(yīng)如下:
app.use(bodyparser({ onerror: function (err, ctx) { ctx.throw('body parse error', 422); } }));
- disableBodyParser:可以通過設(shè)置ctx動態(tài)禁用body解析器。disableBodyParser = true。
app.use(async (ctx, next) => { if (ctx.path === '/disable') ctx.disableBodyParser = true; await next(); }); app.use(bodyparser());
koa-logger
請求響應(yīng)監(jiān)聽日志
下載
npm i koa-logger
使用
~~// 引入日志中間件 const logger = require('koa-logger'); // 注冊日志中間件 app.use(logger()); ~~
koa-session
用于Koa的簡單會話中間件。默認(rèn)為基于cookie的會話,并支持外部存儲。
session
我們知道,http協(xié)議是無狀態(tài)的,當(dāng)用戶進(jìn)行登錄后,并不會保存賬戶密碼,如果我們需要維持用戶的登錄狀態(tài),就需要使用一些方法。目前主流的用戶認(rèn)證方法有基于token和基于session兩種方式。
基于token的認(rèn)證可以使用koa-jwt中間件,基于session的認(rèn)證則使用標(biāo)題的koa-session。
下載
npm i koa-session
使用
app.js 入口文件中注冊session
const CONFIG = { key: 'koa:sess', /\*\* (string) cookie key (default is koa:sess) \*/ /\*\* (number || 'session') maxAge in ms (default is 1 days) \*/ // 狀態(tài)保存最大時間,默認(rèn)為一天 maxAge: 86400000, autoCommit: true, /\*\* (boolean) 自動保存頭部 (default true) \*/ overwrite: true, /\*\* (boolean) 能否覆蓋 (default true) \*/ httpOnly: true, /\*\* (boolean) httpOnly or not (default true) \*/ signed: true, /\*\* (boolean) signed or not (default true) \*/ /\*\* (boolean) 強(qiáng)制在每個響應(yīng)上設(shè)置會話標(biāo)識符cookie。過期將重置為原始maxAge,重新設(shè)置過期倒計(jì)時。 (default is false) \*/ rolling: false, /\*\* (boolean) 當(dāng)會話快過期時續(xù)訂會話,這樣我們可以始終保持用戶登錄。(default is false)\*/ renew: false, }; // 如果你所有都為默認(rèn)配置,則不需要傳遞配置參數(shù),app.use(session(app))即可 app.use(session(sessionConfig, app));
session的使用
注冊后可以通過上下文ctx找到session屬性,下面代碼將用戶信息存入session屬性中,并創(chuàng)建key和value
user.js
// 用戶登錄 static async login(ctx, next) { const data = ctx.request.body const schema = Joi.object().keys({ username: Joi.string().required(), password: Joi.string().required(), }) let result = Joi.validate(data, schema) // 如果有字段類型錯誤 if(result.error) { return ctx.response.body = { status: 400, msg: result.error.details}; } let { username, password } = result.value // 驗(yàn)證過后的數(shù)據(jù) // 查找是否有該用戶 const userInfo = await usersModel.findByName(username) // 如果有該用戶,繼續(xù)驗(yàn)證密碼是否正確 if (userInfo) { const userInfo2 = await usersModel.findOne({ username, password }) if (userInfo2) { ctx.response.body = {state: 200, msg: '登錄成功'} // 設(shè)置session ctx.session.userInfo = userInfo2 } else { ctx.response.body = {state: 410, msg: '密碼錯誤'} } // 如果沒有該用戶,返回結(jié)果 } else { ctx.response.body = {state: 410, msg: '該用戶不存在'} } return ctx.response.body }
koa-router路由中間件中驗(yàn)證session,這里需要注意的是next()方法前一定要使用await,不然程序不會等待next()方法執(zhí)行。
export const verifyUser = async (ctx, next) => { if (ctx.session.userInfo) { await next() } else { return ctx.response.body = { state: 401, msg: '無權(quán)限訪問' } } }
koa2-cors
用于解決跨域問題
下載
npm install koa2-cors
使用
app.use(cors())
到此這篇關(guān)于koa2的中間件功能及應(yīng)用示例的文章就介紹到這了,更多相關(guān)koa2 中間件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodejs連接mysql數(shù)據(jù)庫簡單封裝示例-mysql模塊
本篇文章主要介紹了nodejs連接mysql數(shù)據(jù)庫簡單封裝(mysql模塊),具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04node.js中事件觸發(fā)器events的使用方法實(shí)例分析
這篇文章主要介紹了node.js中事件觸發(fā)器events的使用方法,結(jié)合實(shí)例形式分析了node.js事件觸發(fā)器events的功能、原理及基本使用方法,需要的朋友可以參考下2019-11-11使用socket.io實(shí)現(xiàn)簡單聊天室案例
這篇文章主要介紹了使用socket.io實(shí)現(xiàn)簡單聊天室案例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01NodeJs內(nèi)存占用過高的排查實(shí)戰(zhàn)記錄
這篇文章主要給大家介紹了關(guān)于NodeJs內(nèi)存占用過高的排查實(shí)戰(zhàn)記錄,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05