const Koa = require("koa");
let app = new Koa();
// ctx : context
// app.use(async (ctx,next)=>{
// // ctx.request === req; 所有的请求信息都在这里
// // ctx.response === res; 所有的响应信息都在这里
// // ctx.response.body = "hello world";
// ctx.body = "你好,世界"
// });
let m1 = async function (ctx, next) {
// console.log("m1````");
// cts.state 传递数据
// 它就像一个中间件的共享空间
ctx.state = {
perPage: 5,
totalPage: "13"
}
// 将控制权交给下一个中间件
next(); // --> 调用下一位 === m2
// console.log("m1 end");
}
let m2 = async function (ctx, next) {
// console.log("m2````");
console.log(ctx.state);
ctx.state = {
p: 1,
id: 14,
totalPage: 3
};
next();// --> 调用下一个
// console.log("m2 end");
}
let m3 = async function (ctx, next) {
// console.log("m3````");
console.log(ctx.state);
ctx.body = "hello";
// 状态码 --> 一般不要修改,没有实际意义,还容易报错
// ctx.status = 404;
}
// 中间件在实际使用,全部都是模块
app.use(m1);
app.use(m2);
app.use(m3);
app.listen(8899);