1-1配置路由
// 没有写路径的包,默认会从node-modules这个文件夹中导入const koa = require('koa')// 导入路由const router = require('koa-router')()//这里等于const router = new router()// 通过new新建一个应用const app = new koa()// 新建一个路由router.get("/my",async ctx=>{ ctx.body = { code:200, msg:'my' }})router.get("/firend",async ctx=>{ ctx.body = { code:200, msg:"friend" }})//引用路由app.use(router.routes())app.listen(8000,()=>{ console.log('服务器打开了');})
2、中间件函数
app.use(async (ctx,next)=>{ console.log(1); await next() //控制往下执行路由})每一个路由都必须经过中间件函数,如果在中间件函数中不写await next(),那么就会被卡在中间件函数,不往下执行了。
app.use(async (ctx,next)=>{ console.log("蛋壳--左") await next() console.log("蛋壳--右")})app.use(async (ctx,next)=>{ console.log("蛋白--左") await next() console.log("蛋白--右")})app.use(async (ctx,next)=>{ console.log("蛋黄")})输出流程# 蛋壳--左,蛋白--左,蛋黄,蛋白--右,蛋壳--右