共计 1467 个字符,预计需要花费 4 分钟才能阅读完成。
一、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. 重定向
编码
router.get("/foo", (ctx) => {ctx.body = "foo page";}); | |
// 重定向针对的是同步申请 | |
router.get("/bar", (ctx) => {ctx.redirect("/foo"); | |
}); |
2. 异步中间件
编码
router.get("/page", async (ctx) => {const data = await util.promisify(readFile)("./public/views/index.html"); | |
ctx.type = "html"; | |
ctx.body = data; | |
}); |
3. 谬误捕捉
倡议所有的处理函数都写成 async 模式,调用 next 函数时加上 await
编码
形式一:自定义中间件
// 写在最后面,因为是洋葱模型,能够捕捉外部所有中间件的谬误 | |
app.use(async (ctx) => { | |
try {await next(); | |
} catch (err) { | |
// 触发 app 的 err 事件 | |
ctx.app.emit('error',err,ctx); | |
ctx.throw(404); // 500 Internal Server Error; 404 Not Found | |
} | |
}); | |
app.use(ctx=>{JSON.parse('jfskdjfsl') | |
}) |
形式二:监听 app 的 error 事件
app.on('error',err=>{console.log('app err',err.message) | |
}) |
正文完