爱学习的好孩子

How to access path & query params in Oak?

时间: 2024-06-14

P - indicates path param

Q - indicates query param

比如:

http://localhost:8080/products/101/review/201?sort=recent&limit=100
                                P          P          Q          Q 

我们写一个例子来说明:

import { Application } from "jsr:@oak/oak@16.1.0/application";
import { Router } from "jsr:@oak/oak@16.1.0/router";

const app = new Application();
const router = new Router();
router.get("/books", (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: 80 });

然后运行deno run --allow-net app.ts

$ curl "http://localhost/products/101/images/201?a=b&c=d"
QUERY PARAMS:
a:b
c:d
PATH PARAMS:
{ prdId: "101", imgId: "201" }

评论