Koa基本使用

2年前 (2022) 程序员胖胖胖虎阿
159 0 0

一、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)
})
版权声明:程序员胖胖胖虎阿 发表于 2022年11月21日 上午2:08。
转载请注明:Koa基本使用 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...