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.处理跨域
依赖安装
npm i @koa/cors编码
const cors = require("@koa/cors");
app.use(
cors({
origin: "*",
})
);2.处理post带参
依赖安装
npm i koa-body编码
const koaBody = require("koa-body");
app.use(koaBody());四、其它
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)
})
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论