一、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)
})
发表回复