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

2 javascript node.js express koa

app.js

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

app.use(bodyParser());
app.use(route.get('/objects/', objects.all));
Run Code Online (Sandbox Code Playgroud)

objects.js

module.exports.all = function * all(next) {
  this.body = yield objects.find({});
};
Run Code Online (Sandbox Code Playgroud)

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

saa*_*adq 6

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

例如,如果请求来自网址,/objects?city=Toronto&color=green您将获得以下内容:

function * routeHandler (next) {
  console.log(this.query.city) // 'Toronto'
  console.log(this.query.color) // 'green'
}
Run Code Online (Sandbox Code Playgroud)

如果要访问整个查询字符串,可以this.querystring改用.您可以在文档中阅读更多相关信息.


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