koa-中间件

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值