Search code examples
node.jskoa

How to check the content of Koa's ctx.query?


For a Koa-based API server, I want to check what parameters the URL query contains.

My setup looks as simple as this:

const Koa = require('koa')
const app = new Koa()

const Router = require('koa-router')
router = new Router()

router.get('/', ctx => {
    console.log(ctx.query)
})

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

app.listen(3000)

It seems that ctx.query has a structure like an object but doesn't work as one.

Methods like ctx.query.hasOwnProperty() or ctx.query.toString() result in an error saying that it is not a function.

Though, Object.keys(ctx.query) gives an array of the keys—which is confusing to me because it apparently is an object and should have above methods.

What is ctx.query exactly? How can I make the failing methods from above working?


Solution

  • ctx.query is the return from Node.js' querystring.parse() method. From the documentation:

    The object returned by the querystring.parse() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

    You can check Koa's request implementation.