koa2的动态路由及get传值取值

浏览器调用

http://localhost:3000/?aid=00

运行项目控制台查看
// 引入koa和路由模块
let Koa = require('koa');
let router = require('koa-router')();

// 实例化
let app = new Koa();

router.get('/', async (ctx, next) => {
    ctx.body = "首页";

    /**
     * 在 koa2 中 GET 传值通过 request 接收,但是接收的方法有两种:query 和 querystring。
     * query:返回的是格式化好的参数对象。 
     * querystring:返回的是请求字符串。
     */

    //  从ctx读取get传值
    console.log(ctx);
    console.log(ctx.query);
    console.log(ctx.querystring);
    console.log(ctx.url);

    // ctx里面的request里面获取get传值
    console.log(ctx.request);
    console.log(ctx.request.query);
    console.log(ctx.request.querystring);
    console.log(ctx.request.url);
})

router.get('/news', async (ctx, next) => {
    ctx.body = "新闻";
});

// 动态路由传递一个值
router.get('/newsDetail/:id', async (ctx, next) => {

    ctx.body = '新闻详情';

    // 获取动态路由的传值 http://localhost:3000/newsDetail/002
    console.log(ctx.params); // { id: '002' }
});

// 动态路由传递多个值
router.get('/product/:id/:name', async (ctx, next) => {

    ctx.body = '产品';
    
    // 获取动态路由的传值 http://localhost:3000/product/002/衣服
    console.log(ctx.params); // { id: '002', name: '衣服' }
});

app
    .use(router.routes())
    .use(router.allowedMethods());

// 监听端口
app.listen(3000);
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值