How to get a query parameter in koa?

Member

by lizzie , in category: Javascript , a year ago

How to get a query parameter in koa?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , a year 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.

Related Threads:

How to get query parameter in Drupal 8?
How to pass a parameter in koa middleware?
How to set query parameter in storybook?
How to pass a parameter into a long query in teradata
How to make an query parameter optional in regex?
How to get more than one parameter using codeigniter?