关于koa2:Koa基本使用

一、koa根本应用依赖装置 npm i koa编码 const Koa = require("koa");const app = new Koa();app.use(async ctx=>{ ctx.body = 'hello Koa';});app.listen('5505',()=>{ console.log('Server running at http://localhost:5505');});二、Koa罕用中间件1.路由依赖装置 npm i @koa/router编码 const Router = require('@koa/router');const router = new Router();router.get('/foo',ctx=>{ ctx.body =' this is foo page';});app.use(router.routes()).use(router.allowedMethods());2.动态资源托管依赖装置 npm i koa-static koa-mount编码 const static = require("koa-static");const path = require("path");const mount = require("koa-mount");// mount 可用于给中间件增加一个路由,这里给托管的动态资源增加一个/public路由前缀app.use(mount("/public", static(path.join(__dirname, "./public"))));3.合并中间件依赖装置 npm i koa-compose编码 const compose = require('koa-compose')const a1 = (ctx,next)=>{ console.log('a1'); next();}const a2 = (ctx,next)=>{ console.log('a2'); next();}const a3 = (ctx,next)=>{ console.log('a3'); next();}app.use(compose([a1,a2,a3]))三、罕用性能1.重定向编码 ...

September 5, 2022 · 1 min · jiezi

关于koa2:koa2洋葱模型的实现

koa2的洋葱模型构造像洋葱 申请过程穿梭洋葱,有个来回外围代码:// 函数集(相当于中间件汇合)let arr = [ (next) => { console.log('a1'); next(); console.log('a2'); }, (next) => { console.log('b1'); next(); console.log('b2'); }, (next) => { console.log('c1'); next(); console.log('c2'); },];// 用递归实现洋葱模型let dispatch = (i) => { let fn = arr[i]; if (typeof fn !== 'function') return let next = () => dispatch(i + 1); fn(next)}dispatch(0)// 运行后果 ==> a1 > b1 > c1 > c2 > b2 > a1包装一下,用中间件形式调用.let a = (next) => { console.log('a1'); next(); console.log('a2');}let b = (next) => { console.log('b1'); next(); console.log('b2');}let c = (next) => { console.log('c1'); next(); console.log('c2');}let compose = (arr) => { return (args) => { console.log(args); let dispatch = (index) => { let fn = arr[index]; if (typeof fn !== 'function') return let next = () => dispatch(index + 1); fn(next); } dispatch(0) }}compose([a, b, c])('内部参数');完

May 15, 2021 · 1 min · jiezi