如何使用 koa-bodyparser 在 koa 中获取查询字符串?

How to get query string in koa with koa-bodyparser?

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 How to use "city=Toronto" in my objects.js?

您可以使用 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