当前位置: 首页 > 工具软件 > quick-query > 使用案例 >

koa-router get请求获取query参数

谭玉泽
2023-12-01

目录

get请求获取query参数


实现方式:

request.query                      query对象

request.querystring             query 字符串

例如: http://localhost:3000/news?a=36&b=37

request.query                      {a:36,b:37}

request.querystring             'a=36&b=37'

案例:

启用下面服务访问该url:http://localhost:3000/news?a=36&b=37

/**
 * Koa
 * */
const Koa = require('koa');
const Router = require('koa-router')();
const App = new Koa();

Router.get('/',(ctx,next)=>{
    ctx.body = 'Hello koa';
});
Router.get('/news',(ctx,next)=>{
   let url = ctx.url;
   let request = ctx.request;
   let req_query = request.query;
   let req_querystring = request.querystring;

   let ctx_query = ctx.query;
   let ctx_querystring = ctx.querystring;
   ctx.body = {
       url,
       req_query,
       req_querystring,
       ctx_query,
       ctx_querystring
   }
});

App.use(Router.routes());
App.use(Router.allowedMethods());
App.listen(3000,()=>{
    console.log('quick start at port 3000');
});

结果:

{"url":"/news?a=36&b=37","req_query":{"a":"36","b":"37"},"req_querystring":"a=36&b=37","ctx_query":{"a":"36","b":"37"},"ctx_querystring":"a=36&b=37"}
 类似资料: