koa【03】路由级中间件

/*
 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(new Date()); //返回当前日期时间 2021-01-21T16:31:36.278Z
  await next(); //当前路由匹配完成后继续向下匹配
});

// 配置路由,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();
  })
  .get("/news", async (ctx) => {
    ctx.body = "这是新闻页面2";
  });
// 也可以如下写法
router.get("/newscontent", async (ctx) => {
  ctx.body = "新闻详情页面";
});

/*
  //作用:启动路由
  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");

 

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