koa【05】中间件的执行流程

/*
Koa 的中间件,无论写在前面还是后面,都会先执行中间件的代码,
 */
/*
 Koa 路由 get 传值
在 Koa2 中 GET 传值通过request接收,但是接收的方法有两种: query 和 querystring
query : 返回的是格式化好的参数对象
querystring : 返回的是请求字符串

 */

// 引入模块
const Koa = require("koa");
const router = require("koa-router")(); //引入和实例化路由

// 实例化
var app = new Koa();
// Koa 中间件
/* 以下中间件中,有两个参数,路由地址和函数 ,没有路由只写函数的话,表示   匹配任何路由   ;
如果没有 next ,路由终止, 参数且执行next()函数,则无法向下继续执行;
如果不写 next , 这个路由被匹配到了之后就不会继续向下匹配。
*/

// app.use(async (ctx) => {
//   console.log(new Date()); //返回当前日期时间 2021-01-21T16:31:36.278Z
// });

app.use(async (ctx, next) => {
  console.log("中间件A:第一步a1执行");
  await next();
  console.log("中间件A:倒数第一步a2执行");
});

// 配置路由,ctx (上下万 context) 整合了 response 和 reject
router
  .get("/", async (ctx) => {
    ctx.body = "hi 首页123"; //返回数据  相当于 res.writeHead()  res.end()
  })
  .get("/news", async (ctx, next) => {
    // 与先的路由相同,也可以写成两个,
    console.log("这是路由中间件1");
    ctx.body = "这是新闻页面1";
    await next(); //这里使用了 await next() ,将会继续向下匹配符合条件的路由,所以 ctx.body 浏览器页面出现的是新闻页面2
  })
  .get("/news", async (ctx) => {
    console.log("所有中间件顺着执行完后,执行路由里边的代码,路由执行完成,再倒回去执行中间件的。");
    console.log("页面2");
    ctx.body = "这是新闻页面2";
  });
// 也可以如下写法
router.get("/newscontent", async (ctx) => {
  ctx.body = "新闻详情页面";
});

//

/*
Koa 的中间件,无论写在路由前面还是后面,都会先执行中间件的代码,
相比 Express, Express 是匹配到相应的路由后就不继续向下匹配了。
 */

app.use(async (ctx, next) => {
  console.log("中间件B:第二步b1执行");
  await next();
  console.log("中间件B:倒数第二步b2执行");
});

/*
  //作用:启动路由
  app.use(router.routes())  

  //作用:这是官方推荐的用法,建议使用
  //我们可以看到 router.allowedMethods() 用在了路由匹配 router.routes() 之后,
  //所以在当所有路由中间件最后调用,此时根据 ctx.status 设置 response 响应头
  app.use(router.allowedMethods())  

  app.use(router.allowOrgins()) //跨域使用
*/
app.use(router.routes()).use(router.allowedMethods());
app.listen(3002);
console.log("http://localhost:3002");

/*
访问  http://localhost:3002/news 的时候,执行顺序如下:

中间件A:第一步a1执行
中间件B:第二步b1执行
这是路由中间件1
所有中间件顺着执行完后,执行路由里边的代码,路由执行完成,再倒回去执行中间件的。
页面2
中间件B:倒数第二步b2执行
中间件A:倒数第一步a2执行

 */

 

posted @ 2021-01-23 12:28  半遮  阅读(228)  评论(0编辑  收藏  举报