zoukankan      html  css  js  c++  java
  • koa 基础(八)koa 中间件的执行顺序

    1.koa 中间件的执行顺序

    app.js

    /**
     * koa 中间件的执行顺序
     */
    // 引入模块
    const Koa = require('koa');
    const router = require('koa-router')(); /*引入是实例化路由 推荐*/
    
    // 实例化
    let app = new Koa();
    
    // Koa中间件
    // 匹配任何路由,如果不写next,这个路由被匹配到了就不会继续向下匹配
    
    // www.域名.com/news
    app.use(async (ctx, next) => {
      console.log('1、这是一个中间件01');
      await next();
    
      console.log('5、匹配路由完成以后又会返回来执行中间件');
    })
    
    app.use(async (ctx, next) => {
      console.log('2、这是一个中间件02');
      await next();
    
      console.log('4、匹配路由完成以后又会返回来执行中间件');
    })
    
    router.get('/', async (ctx) => {
      ctx.body = '首页';
    })
    
    router.get('/news', async (ctx) => {
      console.log('3、匹配到了news这个路由');
      ctx.body = '这是一个新闻页面';
    })
    
    router.get('/login', async (ctx) => {
      ctx.body = '登录页面';
    })
    
    app.use(router.routes());
    app.use(router.allowedMethods());
    /**
     * router.allowedMethods() 作用:这是官方文档的推荐用法,我们可以
     * 看到 router.allowedMethods() 用在了路由匹配 router.routes()之后,
     * 所以在当所有路由中间件最后调用,此时根据 ctx.status 设置 response 响应头
     */
    
    app.listen(3000);

    .

  • 相关阅读:
    ReentrantLock类详解
    Linux中 docker安装
    canvas画图练习教程
    Axure 9 使用笔记
    设计模式9—工厂模式【创建型】
    Docker 快速部署 MySQL
    Laravel Sanctum SPA cookie&session 验证实践
    地图地区生成随机点
    Laravel Class 'DoctrineDBALDriverPDOMySqlDriver' not found
    LightHouse 自定义参数指令 (Argument Directives)
  • 原文地址:https://www.cnblogs.com/crazycode2/p/10858679.html
Copyright © 2011-2022 走看看