
const koa = require("koa")const app = new koa();//app.use(fn) fn--中间件//中间件:路由匹配之前和路由完成之后要进行的一些操作就加中间件app.use(async (ctx,next) => { console.log("fn1") var res = await next() console.log(res) console.log("4")})app.use(async (ctx,next) => { console.log("fn2") await next(); console.log("3") return "second"})app.listen(8080)//f1 f2 3 second 4
const koa = require("koa")const app = new koa();const router = require("koa-router")()//如果没有next,下一个中间函数上周执行//每读一个路由页面,都会经过这个中间件函数app.use(async(ctx,next) => { console.log("login") console.log(ctx.path) //可以获取路由的路径 if (ctx.path == "/user") { } else { ctx.body = "不许看" } await next()})router.get("/", async ctx => { ctx.body="首页"})router.get("/user", async ctx => { ctx.body="核心密码"})router.get("/my", async ctx => { ctx.body="my"})app.use(router.routes());app.listen(8080)