如存在两个中间件 就要有两个参数哦 ctx next 并且await next 不然下一个中间件就执行不了
最后一个中间件不用await next

执行流程
await 将函数切割了 只有next中的函数执行完毕之后 才会执行上一段中间函数中await后面的内容
![C_X($D{T~SHS7(%(FEEY.png
CZE4$DQJDAJ_C~AL1475WBA.png

  1. const koa = require("koa")
  2. const app = new koa()
  3. //app.use(fn) fn--中间件
  4. //中间件:路由匹配之前和路由完成之后要进行的一些操作就叫中间件
  5. //中间件函数有两个参数:ctx next
  6. //next 指的是下一个中间件函数
  7. //洋葱模型
  8. app.use(async (ctx, next) => {
  9. console.log("fn1")
  10. var res = await next()
  11. console.log(res);
  12. console.log(4);
  13. })
  14. //next=相等于下面的async ctx => {
  15. // console.log("fn2");
  16. // })
  17. app.use(async (ctx, next) => {
  18. console.log("fn2");
  19. await next()
  20. console.log(3);
  21. return "second"
  22. })
  23. // fn1
  24. // fn2
  25. // 3
  26. // second
  27. // 4
  28. app.listen(8080)

image.png
image.png

模拟没有登录进不去 没有next所以后面的的hello核心密码都进不去

  1. const koa = require("koa")
  2. const app = new koa()
  3. const router = require("koa-router")()
  4. //如果没有netx 下一个中间函数不会执行
  5. app.use((ctx, next) => {
  6. console.log("login");
  7. })
  8. router.get("/", async ctx => {
  9. ctx.body="hello"
  10. })
  11. router.get("/user", async ctx => {
  12. ctx.body="核心密码"
  13. })
  14. app.use(router.routes())
  15. app.listen(8080)

使用中间件过滤(未登录不让登录)

  1. const koa = require("koa")
  2. const app = new koa()
  3. const router = require("koa-router")()
  4. //如果没有netx 下一个中间函数不会执行
  5. //每读取一个路由页面 都会经过这个中间件函数
  6. app.use(async (ctx, next) => {
  7. console.log("login")
  8. console.log(ctx.path);
  9. //ctx.path可以获取路由的路径
  10. if (ctx.path == "/user") {
  11. ctx.body == "请登录"
  12. } else {
  13. await next();
  14. }
  15. })
  16. router.get("/", async ctx => {
  17. ctx.body = "hello"
  18. })
  19. router.get("/user", async ctx => {
  20. ctx.body = "核心密码"
  21. })
  22. router.get("/my", async ctx => {
  23. ctx.body = "my"
  24. })
  25. app.use(router.routes())
  26. app.listen(8080)