Deno nuggets: Get path and query params in Oak
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to access path & query params in Oak?
P-indicates path param
Q-indicates query param
http://localhost:8080/products/101/review/201?sort=recent&limit=100
P P Q Q
Solution
Oak middleware framework automatically parses the path and query params. No explicit parsing is required. Both type of params are accessed from different places and in different ways.
Query params
Query params are accessed through the searchParams (of type URLSearchParams) attribute in context’s request’s url object. The URLSearchParams is a web standard object with APIs like has, get, entries, etc.
ctx.request.url.searchParams
ctx.request.url.searchParams.get('someParam');
Path params
The path params are available at context level in params attribute. It’s a simple JS object.
ctx.params.someParam
ctx.params.someOtherParam
Here is the code of an application that prints both the query and path params:
import { Application, Router } from "https://deno.land/x/oak/mod.ts";const app = new Application();
const router = new Router();router.get("/products/:prdId/images/:imgId", (ctx) => {
console.log("QUERY PARAMS:");
ctx.request.url.searchParams.forEach((v, k) => console.log(`${k}:${v}`));
console.log("PATH PARAMS:");
console.log(ctx.params);
});app.use(router.routes());
app.use(router.allowedMethods());
app.listen({ port: 8080 });
Here is a quick run:
> curl "http://localhost:8080/products/101/images/201?a=b&c=d"> > deno run --allow-net app.ts
QUERY PARAMS:
a:b
c:d
PATH PARAMS:
{ prdId: "101", imgId: "201" }