【问题标题】:How to get query string in koa with koa-bodyparser?如何使用 koa-bodyparser 在 koa 中获取查询字符串?
【发布时间】:2026-01-06 19:15:01
【问题描述】:

app.js

var bodyParser = require('koa-bodyparser');

app.use(bodyParser());
app.use(route.get('/objects/', objects.all));

objects.js

module.exports.all = function * all(next) {
  this.body = yield objects.find({});
};

这适用于获取所有对象。但我想通过查询参数获取,例如 localhost:3000/objects?city=Toronto 如何在我的 objects.js 中使用“city=Toronto”?

【问题讨论】:

    标签: javascript node.js express koa


    【解决方案1】:

    您可以使用this.query 访问您的所有查询参数。

    例如,如果请求来自 URL /objects?city=Toronto&color=green,您将获得以下信息:

    function * routeHandler (next) {
      console.log(this.query.city) // 'Toronto'
      console.log(this.query.color) // 'green'
    }
    

    如果您想访问整个查询字符串,您可以改用this.querystring。您可以在docs 中了解更多信息。


    编辑:使用 Koa v2,您将使用 ctx.query 而不是 this.query

    【讨论】: