48

I'm using koa-router.

How can I get the request's query string params?

This is the best I managed to write:

import koaRouter from 'koa-router';

const router = koaRouter({ prefix: '/courses' });

router.get('/', async (ctx) => {
        console.log(ctx.qs["lecturer"]);
    });

but qs is undefined

Any help will be profoundly appreciated!

Alon
  • 10,381
  • 23
  • 88
  • 152

2 Answers2

90

According to the docs there should be a ctx.request.query that is the query string items represented as an object.

CodingWithSpike
  • 42,906
  • 18
  • 101
  • 138
  • 2
    ctx.request.query is undefined, although ctx.request.url is '/api/courses?lecturer=John_Smith' – Alon Apr 06 '17 at 14:55
  • @Alon how are you mounting the router onto the app? – robertklep Apr 09 '17 at 10:13
  • 1
    I don't know what was changed, but suddenly ctx.request.query is working – Alon Apr 09 '17 at 10:41
  • 3
    @JosephAstrahan you will need to revisit your edit and comment. That's quite misleading comment and edit there. @Cory Robinson is right. It should simply be `ctx.query` which comes from `koa` where `koa-router` just passes along with the request [as mentioned here](https://koajs.com/#request). Had the OP asked just for "url params" then you'd be right but the question is about "query string" params. Not the same thing. – shriek Jun 24 '19 at 05:03
  • This answer is wrong. The correct usage is `ctx.request.query` (or the alias `ctx.query`) at the time of this writing. – Martin Wickman Sep 11 '19 at 11:15
  • I undid the edit that added incorrect information and code sample. – CodingWithSpike Sep 13 '19 at 14:36
  • How to get url params instead of query? – sumit_suthar Feb 13 '20 at 11:20
28

You can use ctx.query (or long-hand ctx.request.query)

app.use( (ctx) => console.log(ctx.query) )

Cory Robinson
  • 4,616
  • 4
  • 36
  • 53
  • Interesting that my WebStorm does not show such property 'ctx.query' at ctx inspecting in debugger, but at direct access it does work. – Dzenly Dec 25 '18 at 10:59
  • 1
    @dzenly this is because that's actually a shortcut (getter), the actual path is `ctx.request.query` – Cory Robinson Dec 27 '18 at 17:07