乐闻世界logo
搜索文章和话题

How to get query string params in koa router?

1个答案

1

According to the documentation, there is a ctx.request.query that represents query string parameters as an object. You can use ctx.query (or the long-hand ctx.request.query).

javascript
app.use( (ctx) => console.log(ctx.query) )

When using Koa Router to handle routes in Koa, you can access query string parameters via ctx.query. ctx is the context object of Koa, which encapsulates the request and response objects.

Here are the steps and examples for retrieving query string parameters:

Step 1: Import Koa and Koa Router

First, you need to install and import the Koa and Koa Router modules.

javascript
const Koa = require('koa'); const Router = require('@koa/router'); const app = new Koa(); const router = new Router();

Step 2: Use Route Middleware to Handle Query Parameters

Next, create a route and access the query parameters within the callback function.

javascript
router.get('/some-path', (ctx) => { // Retrieve query parameters const queryParams = ctx.query; // Process the query parameters // ... ctx.body = { message: 'View query parameters', queryParams }; }); // Apply route middleware app.use(router.routes()).use(router.allowedMethods());

In the above example, when a request is sent to /some-path, we retrieve the query parameters using ctx.query, which is an object containing all query string parameters from the request. If the request URL is /some-path?name=John&age=30, then ctx.query will be { name: 'John', age: '30' }.

Step 3: Start the Koa Application

javascript
const port = 3000; app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });

Example

If you receive a GET request with the URL http://localhost:3000/some-path?user=alice&token=123, you can retrieve these parameters as follows:

javascript
router.get('/some-path', (ctx) => { const user = ctx.query.user; // alice const token = ctx.query.token; // 123 // ... Process these parameters according to business logic ctx.body = { message: 'Retrieved user information', user, token }; });

This way, you can process these parameters according to business requirements, such as validating the token's validity or retrieving user information.

In summary, retrieving query string parameters with Koa Router is done directly through the query property of the context object ctx, which provides an object containing all query parameters, making it intuitive and convenient.

2024年6月29日 12:07 回复

你的答案