如何查看Koa的ctx.query的内容?

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

对于基于 Koa 的 API 服务器,我想检查 URL 查询包含哪些参数。

我的设置看起来很简单:

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)

似乎 ctx.query 具有类似对象的结构,但不能作为一个对象使用。

ctx.query.hasOwnProperty()ctx.query.toString() 等方法会导致错误提示它不是函数。

不过,Object.keys(ctx.query) 给出了一个键数组——这让我感到困惑,因为它显然 一个对象并且应该具有上述方法。

ctx.query 到底是什么?如何使上述失败的方法起作用?

ctx.query 是 Node.js' querystring.parse() 方法中的 return。来自文档:

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.

你可以查看 Koa 的 request implementation