Skip to content
大纲

基本使用

启动服务

shell
npm i koa
js
import Koa from "koa";
const app = new Koa();
app.use(ctx => (ctx.body = "Hello Koa")).listen(80);

中间件

使用 app.use(middleware) 可以引用中间件,支持 async functoncommon function

  • 第一个参数为上下文,其对 http 请求和响应进行了封装
  • 第二个参数为 next,作用是调用下游中间件,并返回一个 Promise
js
// use async function
// 这里的输出结果表示执行的顺序
app.use(async (ctx, next) => {
  await console.log(1);
  await console.log(2);
  await next();
  console.log(6);
  ctx.body = "hello";
});

app.use(async (ctx, next) => {
  await console.log(3);
  await next();
  console.log(5);
});

app.use(async (ctx, next) => {
  await console.log(4);
});
js
// use common function
//这里的输出结果表示执行的顺序
app.use((ctx, next) => {
  console.log(1);
  next();
  console.log(5);
  ctx.body = "hello";
});
app.use((ctx, next) => {
  console.log(2);
  next();
  console.log(4);
});
app.use((ctx, next) => {
  console.log(3);
});

Context

  • Context 对象对 node 的 requestresponse 对象进行了封装
  • app.context 可以扩展全局上下文, 中间件中为其实例, 一般使用 ctx 简写
js
app.context.name = "test";
app.use(ctx => {
  console.log(ctx.name);
});

常见属性

  • ctx.req: node 中的 request 对象
  • ctx.res: node 中的 response 对象
  • ctx.request: Koa 封装的 request 对象
  • ctx.response: Koa 封装的 response 对象
  • ctx.state: 建议使用的命名空间,便于通过中间件进行数据传递
  • ctx.app: 应用程序的实例引用

常见方法

  • ctx.throw([status, [msg, [properties]]]): 抛出异常
  • ctx.cookies.set(name, value[, options]): 设置 cookie
  • ctx.cookies.get(name[, options]): 获取指定 cookie

错误处理

js
app.use(ctx => {
  throw new Error("自定义一个错误");
});

app.on("error", (err, ctx) => {
  console.log(err);
});