1

if a define a route like this:

router.get('/:name/:age', async (ctx, next) => {
  ctx.body = ctx.params
})

when i access the url: http://localhost:3000/vortesnail/18, I'll get:

{ 
  name: 'vortesnail',
  age: '18'
}

Here is my problem: if i access these urls, i want to get all params, what should i do with the router.get('/name/age/????????', async () => {})?

Example:

http://localhost:3000/vortesnail/18/male
http://localhost:3000/vortesnail/18/male/student
http://localhost:3000/vortesnail/18/female
http://localhost:3000/vortesnail/18/female/student/any/any/any/....

vortesnail
  • 31
  • 5

1 Answers1

1

You can substitute the parameters with a wildcard regex:

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

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

router.get("/static-prefix/(.*)?", (ctx, next) => {
  console.log(ctx.params);
});

app.use(router.routes());

app.listen(3000);

Now if you open http://localhost:3000/static-prefix/aa/bb/cc it will print

{ '0': 'aa/bb/cc' }.

From here you can easily split/parse the individual parameters in javascript.

Max Ivanov
  • 5,695
  • 38
  • 52