zoukankan      html  css  js  c++  java
  • koa 基础(六)应用级路由中间件

    1.应用级路由中间件

    app.js

    /**
     * 应用级路由中间件
     */
    // 引入模块
    const Koa = require('koa');
    const router = require('koa-router')(); /*引入是实例化路由 推荐*/
    
    // 实例化
    let app = new Koa();
    
    // Koa中间件
    // 匹配任何路由,如果不写next,这个路由被匹配到了就不会继续向下匹配
    
    router.get('/', async (ctx) => {
      ctx.body = '首页';
    })
    
    router.get('/news', async (ctx, next) => {
      console.log('这是一个新闻1');
      await next();
    })
    
    router.get('/news', async (ctx) => {
      ctx.body = '这是一个新闻2';
    })
    
    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);

    .

  • 相关阅读:
    link和@import区别
    常用的正则表达式
    virtual dom
    git常用命令
    系统管理与进程命令
    Shell 命令
    软件安装命令
    vim 详解
    网络命令
    帮助与用户管理命令
  • 原文地址:https://www.cnblogs.com/crazycode2/p/10850555.html
Copyright © 2011-2022 走看看