koa

159 阅读2分钟

上下文

Koa Context 将 node 的 request 和 response对象以及一些常用的方法如(body,url等)封装在一个单独的对象里面。 不支持绕过ctx对象的res处理

app.use(async (ctx) => {
    ctx; // is the Context
    ctx.request; // is a koa Request
    ctx.response; // is a koa Response
});
app.use(async ctx => {
    // ctx.body = 'hello koa'
    // console.log(ctx.req.method);
    // console.log(ctx.req.url);
    // console.log(ctx.req.headers);
    ctx.status(200).json({msg:'okok'})
})

中间件

最外层的中间件先执行,跟函数的栈执行顺序一样

//one-1 one-2 two-1 two-2
app.use((ctx,next) => {
   console.log('one-1');
   console.log('one-2');
   next()
})
.use(ctx => {
   console.log('two-1');
   console.log('two-2');
})
//one-1 two-1 three-1 three-2 two-2 one-2
app.use((ctx,next) => {
   console.log('one-1');// 1.先执行one-1
   next()//2.next跳到two中间件
   console.log('one-2');//9.执行one-2
})
.use((ctx,next) => {
   console.log('two-1');//3.执行two-1
   next()//4.跳到three中间件
   console.log('two-2');//8.执行two-2,two中间件执行完成,出栈
})
.use((ctx,next) => {
   console.log('three-1');//5.执行three-1
   next()//6.下面没有中间件,处于中间件的最里层,执行下面的
   console.log('three-2');//7.执行three-2,thre中间件执行完成,出栈,执行上一层中间件
})

异步执行

 //one-1 two-1 one-2 three-1 three-2 two-2 
app.use(async (ctx,next) => {
   console.log('one-1');//1
   next()//2
   console.log('one-2');//4
})
.use(async (ctx,next) => {
   await console.log('two-1');//3.因为是异步的原因,所以two-1具有等待的效果,next不会马上执行那就说明当前two中间件的调用栈已经结束,所以执行one中间件
   next()
   console.log('two-2');//8
})
.use(async (ctx,next) => {
   console.log('three-1');//5
   next()//6
   console.log('three-2');//7
})

路由

npm i @koa/router
const Router = require('@koa/router')
const router = new Router({prefix:'/api/v1'}) 

router.get('/user/info',ctx => {
    ctx.body = 'user'
})

app.use(router.routes())
router.get("/user", (ctx) => {
    console.log(ctx.query);
    ctx.body = "123 user";
});
router.get("/video/:id", (ctx) => {
    console.log(ctx.params);
    ctx.body = "123 video";
});
npm i koa-body
const koaBody = require('koa-body')

router.post("/postuser", (ctx) => {
    //url和json
    // console.log(ctx.request.body);
    console.log(ctx.request.files);
    ctx.body = "123 postuser";
});

app.use(koaBody())

异常

//手动

router.post("/postuser", (ctx) => {
    // ctx.throw(400,'400err')
    ctx.throw(500)
});

//自动

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

校验

npm i Joi
const Joi = require("joi");
const { User } = require("../model");

module.exports.registerValidate = async (ctx, next) => {
    const schema = Joi.object({
        username: Joi.string().required(),
        password: Joi.string().min(3).max(20).required(),
        email: Joi.string().email().required(),
        phone: Joi.string().required(),
    }).validate(ctx.request.body);

    if (schema.error) {
        ctx.throw(400, schema.error);
    }
    const e = await User.findOne({ email: ctx.request.body.email });
    if (e) {
        ctx.throw(400, "email已注册");
    }
    await next();
};