zoukankan      html  css  js  c++  java
  • koa 基础(五)动态路由的传值

    1.动态路由的传值 app.js

    /**
     * 动态路由的传值
     */
    // 引入模块
    const Koa = require('koa');
    const router = require('koa-router')(); /*引入是实例化路由 推荐*/
    
    // 实例化
    let app = new Koa();
    
    router.get('/', async (ctx) => {
      ctx.body = '首页';
    })
    
    router.get('/news', async (ctx) => {
      ctx.body = '新闻列表页面';
    })
    
    router.get('/newscontent/:aid', async (ctx) => {
      // 获取动态路由的传值
      console.log(ctx.params); // {aid: '123'}
      ctx.body = '新闻详情';
    })
    
    // 动态路由里面可以传入多个值
    router.get('/package/:aid/:cid', async (ctx) => {
      // 获取动态路由的传值
      console.log(ctx.params); // { aid: '123', cid: '456' }
      ctx.body = 'package详情';
    })
    
    app.use(router.routes());
    app.use(router.allowedMethods());
    /**
     * router.allowedMethods() 作用:这是官方文档的推荐用法,我们可以
     * 看到 router.allowedMethods() 用在了路由匹配 router.routes()之后,
     * 所以在当所有路由中间件最后调用,此时根据 ctx.status 设置 response 响应头
     */
    
    app.listen(3000);

    .

  • 相关阅读:
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Arctic Network POJ
    Truck History POJ
    QS Network ZOJ
  • 原文地址:https://www.cnblogs.com/crazycode2/p/10846861.html
Copyright © 2011-2022 走看看