# Koa
# 安装
npm install koa2
1
npm install kolorist
npm install koa-router
1
2
2
# 简单的例子
// config.js
module.exports = {
httpPort: 5000,
wsPort: 12345
};
1
2
3
4
5
2
3
4
5
// 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}`)}`);
});
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 使用路由
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());
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 洋葱模型
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
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1
2
3
33
22
11
1
2
3
4
5
6
2
3
4
5
6