http url parameters question

Hi yall, I am currently trying to make a Deno http server for the funs, but I am walking into a problem. I want to have 3 pages: /, /thing and /thing/:id. If the route is /, it directs to home, if the route is /thing/:id, then it directs to that page, and if the route is /thing/:id but without a (valid) id, then it directs to /thing. Is there a way to do this without putting the handlers for /thing and /thing/:id in seperate?
7 Replies
Definitely Not A Dolphin
I currently have this code
Definitely Not A Dolphin
Every route is an object of type Route, and my goal is to put bot the code for /thing and /thing/:id in the same function (if that makes sense) currently, / and /thing/:id both work, but typing in /thing directs to /
marvinh.
marvinh.3w ago
that's because once the for-of loop completes and nothing matched, you're calling homeRoute.execute(req). basically your home route is your 404 route
Definitely Not A Dolphin
aha Okay so what do I change so that /thing and /thing/:id both route to the same page then? And after that, how do I / should I seperate the 404 from the home? or should I just make a new Route Object for that i think that is best
sipONE
sipONE3w ago
async function handler(req: Request): Promise<Response> {
for (const route of routes) {
const match = route.url.exec(req.url);
console.log(match ?? "nee");
if (match) return await thingRoute.execute(req, match);
}

return await homeRoute.execute(req);
}
async function handler(req: Request): Promise<Response> {
for (const route of routes) {
const match = route.url.exec(req.url);
console.log(match ?? "nee");
if (match) return await thingRoute.execute(req, match);
}

return await homeRoute.execute(req);
}
re-think this, now if match you get /thing/:id route, but if not what happens? it exits for loop and after that without condition it returns homeroute / could you first check if route is plain / then return homeroute, if not then check for /thing/:id if !match then return /thing/ route.
Definitely Not A Dolphin
I figured that but thanks
async function handler(req: Request): Promise<Response> {
console.log(routes);
for (const route of routes) {
const match = route.url.exec(req.url);
if (match) return await route.execute(req, match);
}

return await route404.execute(req);
}
async function handler(req: Request): Promise<Response> {
console.log(routes);
for (const route of routes) {
const match = route.url.exec(req.url);
if (match) return await route.execute(req, match);
}

return await route404.execute(req);
}
First /thing/:id, then /thing and then /, and then a 404 error

Did you find this page helpful?