How to get a query parameter in koa?

Member

by lizzie , in category: Javascript , 8 months ago

How to get a query parameter in koa?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 8 months ago

@lizzie 

In Koa, you can access query parameters from the request object using the request.query property. Here's an example of how to get a query parameter named "search" in a Koa route handler:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const Koa = require('koa');
const app = new Koa();

app.use(async (ctx) => {
  // Get the value of the "search" query parameter
  const searchQuery = ctx.request.query.search;

  // Do something with the query parameter
  console.log(searchQuery);

  ctx.body = 'Query parameter value: ' + searchQuery;
});

app.listen(3000);


In this example, when you make a GET request to http://localhost:3000/?search=query, the value of the "search" query parameter will be stored in the searchQuery variable and printed to the console. The response body will also include the value of the query parameter.


You can access multiple query parameters by accessing the individual properties of ctx.request.query.