如存在两个中间件 就要有两个参数哦 ctx next 并且await next 不然下一个中间件就执行不了
最后一个中间件不用await next
执行流程
await 将函数切割了 只有next中的函数执行完毕之后 才会执行上一段中间函数中await后面的内容

const koa = require("koa")const app = new koa()//app.use(fn) fn--中间件//中间件:路由匹配之前和路由完成之后要进行的一些操作就叫中间件//中间件函数有两个参数:ctx next//next 指的是下一个中间件函数//洋葱模型app.use(async (ctx, next) => {console.log("fn1")var res = await next()console.log(res);console.log(4);})//next=相等于下面的async ctx => {// console.log("fn2");// })app.use(async (ctx, next) => {console.log("fn2");await next()console.log(3);return "second"})// fn1// fn2// 3// second// 4app.listen(8080)


模拟没有登录进不去 没有next所以后面的的hello核心密码都进不去
const koa = require("koa")const app = new koa()const router = require("koa-router")()//如果没有netx 下一个中间函数不会执行app.use((ctx, next) => {console.log("login");})router.get("/", async ctx => {ctx.body="hello"})router.get("/user", async ctx => {ctx.body="核心密码"})app.use(router.routes())app.listen(8080)
使用中间件过滤(未登录不让登录)
const koa = require("koa")const app = new koa()const router = require("koa-router")()//如果没有netx 下一个中间函数不会执行//每读取一个路由页面 都会经过这个中间件函数app.use(async (ctx, next) => {console.log("login")console.log(ctx.path);//ctx.path可以获取路由的路径if (ctx.path == "/user") {ctx.body == "请登录"} else {await next();}})router.get("/", async ctx => {ctx.body = "hello"})router.get("/user", async ctx => {ctx.body = "核心密码"})router.get("/my", async ctx => {ctx.body = "my"})app.use(router.routes())app.listen(8080)
