# Koa

# 安装

npm install koa2
npm install kolorist
npm install koa-router

# 简单的例子

// config.js
module.exports = {
  httpPort: 5000,
  wsPort: 12345
};
// app.js
const Koa = require("koa2");
const path = require("path");
const { blue, green } = require("kolorist");
const { httpPort } = require("./config");

const app = new Koa();

app.server = app.listen(httpPort, () => {
  console.log(`${blue(`Server is Running`)} at ${green(`http://localhost:${httpPort}`)}`);
});

# 使用路由

const router = new KoaRouter();

router.get("/", async (ctx) => {
  ctx.body = "Home";
});

router.get("/posts", async (ctx) => {
  ctx.body = "Posts";
});

app.use(router.routes(), router.allowedMethods());

# 洋葱模型

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

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

app.use(async (ctx, next) => {
  console.log(3);
  next();
  console.log(33);
});
1
2
3
33
22
11