阿里云主机折上折
  • 微信号
Current Site:Index > Retrieving route parameters and query parameters

Retrieving route parameters and query parameters

Author:Chuan Chen 阅读数:50644人阅读 分类: Node.js

Retrieving Route Parameters

In Koa2, route parameters refer to the dynamic parts of a URL path, typically used to identify specific resources. These parameters are captured through placeholders specified during route definition, with the most common placeholder syntax being :paramName.

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

const app = new Koa();
const router = new Router();

router.get('/users/:id', (ctx) => {
  const userId = ctx.params.id;
  ctx.body = `User ID: ${userId}`;
});

app.use(router.routes());

When accessing /users/123, the ctx.params object will contain { id: '123' }. Characteristics of route parameters include:

  • Must match the corresponding position in the path
  • Parameter values are always of string type
  • Supports defining multiple parameters simultaneously

For more complex matching requirements, regular expressions can be used:

router.get('/articles/:year(\\d{4})/:month(\\d{2})', (ctx) => {
  const { year, month } = ctx.params;
  ctx.body = `Querying articles from ${year}-${month}`;
});

Parsing Query Parameters

Query parameters appear after the question mark in a URL, in key-value pairs. Koa2 provides automatically parsed objects via ctx.query:

router.get('/search', (ctx) => {
  console.log(ctx.query);
  // Accessing /search?q=koa&page=2 outputs: { q: 'koa', page: '2' }
  
  const searchTerm = ctx.query.q || '';
  const page = parseInt(ctx.query.page) || 1;
  ctx.body = `Searching for "${searchTerm}", page ${page}`;
});

To retrieve the raw query string, use ctx.querystring:

router.get('/raw-query', (ctx) => {
  ctx.body = `Raw query string: ${ctx.querystring}`;
  // Accessing /raw-query?name=test&sort=asc outputs: name=test&sort=asc
});

Advanced Parameter Handling Techniques

When dealing with array-style query parameters, Koa2 automatically converts them:

// Accessing /filters?color=red&color=blue
router.get('/filters', (ctx) => {
  console.log(ctx.query.color); // ['red', 'blue']
});

For nested objects, bracket syntax can be used:

// Accessing /complex?user[name]=John&user[age]=30
router.get('/complex', (ctx) => {
  console.log(ctx.query.user); // { name: 'John', age: '30' }
});

Parameter Validation and Conversion

It's recommended to validate and convert parameters:

router.get('/products/:id', (ctx) => {
  const id = parseInt(ctx.params.id);
  if (isNaN(id) || id <= 0) {
    ctx.status = 400;
    ctx.body = { error: 'Invalid product ID' };
    return;
  }
  
  // Process valid ID...
});

For query parameters, use destructuring with default values:

router.get('/list', (ctx) => {
  const { 
    page = 1, 
    limit = 10, 
    sort = 'date' 
  } = ctx.query;
  
  const options = {
    page: Math.max(1, parseInt(page)),
    limit: Math.min(100, Math.max(1, parseInt(limit))),
    sort
  };
  
  // Use options for database queries...
});

Common Issues and Solutions

When route parameters contain special characters, encoding must be considered:

router.get('/files/:name', (ctx) => {
  // Filenames may contain Chinese or special characters
  const fileName = decodeURIComponent(ctx.params.name);
  console.log('Requested file:', fileName);
});

Optional parameters can be handled by defining multiple routes:

router.get('/posts/:year/:month?/:day?', (ctx) => {
  const { year, month, day } = ctx.params;
  if (day) {
    // Query by day
  } else if (month) {
    // Query by month
  } else {
    // Query by year
  }
});

Performance Optimization Tips

For frequently accessed routes, cache parameter parsing results:

const paramCache = new Map();

router.get('/cached/:key', (ctx) => {
  const { key } = ctx.params;
  if (paramCache.has(key)) {
    ctx.body = paramCache.get(key);
    return;
  }
  
  // Time-consuming computation or database query
  const result = expensiveOperation(key);
  paramCache.set(key, result);
  ctx.body = result;
});

When retrieving multiple parameters, consider using object spreading:

router.get('/multi-params/:category/:subcategory', (ctx) => {
  const params = {
    ...ctx.params,
    ...ctx.query,
    timestamp: Date.now()
  };
  
  // Use the merged params object...
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.