D
Deno

help

Get a Parameter Value in Oak

Aalexp9510/27/2023
so if I set up a router like this
router.get("/:id", (ctx) => {/*handle router context*/})
router.get("/:id", (ctx) => {/*handle router context*/})
then how do I get the value of the id parameter? I have tried ctx.id and it did not accept it
DAHDeno AI Helper10/27/2023
To get the value of the id parameter in Oak, you can use the getQuery helper function from Oak's helpers module. Here's how you can do it:
router.get("/:id", (ctx: Context) => {
const { id } = helpers.getQuery(ctx, { mergeParams: true });
// Now you can use the id
});
router.get("/:id", (ctx: Context) => {
const { id } = helpers.getQuery(ctx, { mergeParams: true });
// Now you can use the id
});
In this code, getQuery is used to extract the parameters from the context. The mergeParams option is set to true to merge the named route parameters and the query string parameters into a single object. The id parameter is then destructured from this object.

Looking for more? Join the community!