Search code examples
javascriptnode.jsexpresskoa

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({});
};

This works fine for get all objects. But I wanna get by query param, something like this localhost:3000/objects?city=Toronto How to use "city=Toronto" in my objects.js?


Solution

  • You can use this.query to access all your query parameters.

    For example, if the request came at the url /objects?city=Toronto&color=green you would get the following:

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

    If you want access to the entire querystring, you can use this.querystring instead. You can read more about it in the docs.


    Edit: With Koa v2, you would use ctx.query instead of this.query.