Issue
I am working on deno
equivalent of my node (express)
server application for study purposes and I can't find a way to apply optional
chunks when defining routes
.
For example in express
application i have route: /search/:start/:records?
import { Application } from "https://deno.land/x/abc@v1.3.3/mod.ts";
import { search } from "./controllers/data.ts";
const app = new Application();
const PORT = 80;
app.get("/search/:start/:records?", search);
app.start({ port: PORT });
For my experimentation with deno
i picked lib
abc that seemed similar to express
.
When runtime is launched my old routes are working, except the optional chunk, they are not optional anymore, instead they need to be provided or error 404
is being returned.
Does someone have experience with handling optional parameters and deno
?
Solution
I don't know a whole lot about abc
, but oak
is currently the most commonly-used http server framework for Deno (and I think it would be the analog of Express based on the metric of popularity).
It uses path-to-regexp
for parsing path strings (which is also what Express uses), so it allows for optional parameters using the same syntax with which you're already familiar.
Here's an example of creating a route like the one in your question using Oak, and sending the path parameter values as properties in a JSON response:
import { Application, Router } from "https://deno.land/x/oak@v10.5.1/mod.ts";
const router = new Router();
router.get("/search/:start/:records?", async (ctx, next) => {
const { start, records = null } = ctx.params;
const json = JSON.stringify({ start, records }, null, 2);
ctx.response.body = json;
ctx.response.type = "application/json";
await next();
});
const app = new Application();
app
.use(router.routes())
.use(router.allowedMethods());
await app.listen({ port: 8000 });
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.