koajs / koa

Expressive middleware for node.js using ES2017 async functions
https://koajs.com
MIT License
35.25k stars 3.23k forks source link

Koa 2 ctx.query nesting #697

Closed liangxingchen closed 8 years ago

liangxingchen commented 8 years ago
// When GET /path?a[b]=c
// I think `ctx.query ` should be:
{
   a:{
      b:'c'
   }
}
// But it is
{
   'a[b]':c
}

// Is this a bug?

// if it is, I think
// koa/lib/request.js line 11
const qs = require('querystring');
// should replaced by
const qs = require('qs');
haoxins commented 8 years ago

@liangxingchen you need https://github.com/koajs/qs

lourd commented 8 years ago

Alternatively, you can use the qs module yourself in a middleware and put the parsed result on the context's state, i.e. ctx.state.query = qs.parse(ctx.querystring). That's what I do in my projects.

fl0w commented 8 years ago

If my memory serves me correctly - query parsing is simple by design. Complexities such as depth can be solved in user land, which as you pointed out: qs has done.

tj commented 8 years ago

There's only an implicit spec for nested query strings, which is why it's not in core. If there's ever a real spec then :+1:, until then it's just random semantics that people attempt to derive out of historical use-cases.

jonathanong commented 8 years ago

Yeah I believe they're working on a real spec for nested query strings. The current semantics is prone to security issues, which is why it isn't included with koa.

liangxingchen commented 8 years ago

the koa-qs works good! thank you all!

demisx commented 5 years ago

I second @lourd's approach and would use qs directly instead of going through another npm dependency, especially since it's not being actively maintained:

app.use(async (ctx, next) => {
  ctx.state.query = qs.parse(ctx.querystring)
  await next()
})