0

Following up on Passing route control with optional parameter after root in express?, I'm working on a simple url-shortening app and would like to catch anything afer the url-path-params (/link/:id) into a single variable. E.g., for:

http://localhost:3002/link/XYZ/abc/def?access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer

I hope to get id=XYZ then rest=abc/def?access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer

I tried /link/:id/:rest? but it's not working for the example url.

router.get("/link/:id/:rest?", getLinkAndParams)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

exports.getLinkAndParams = async (req, res) => {
    const id = req.params.id
    let rest = req.params.rest
    rest = rest ? `/${rest}` : ""
...
xpt
  • 20,363
  • 37
  • 127
  • 216

1 Answers1

1

Like this:

routes.get("/link/*", getLinkAndParams);

Example:-

router.get("/link/:id/*", getLinkAndParams);

exports.getLinkAndParams = async (req, res) => {
  const id = req.params.id;
  const rest = req.params[0]; // the rest of the path and query string will be captured in this variable
  console.log(`id: ${id}`);
  console.log(`rest: ${rest}`);
  // ...
};
zain ul din
  • 1
  • 1
  • 2
  • 23
  • @xpt I'm creating a restful-APIs framework if you're interested let me know we're looking for contributors https://github.com/Zain-ul-din https://github.com/RandomsDev Discord id: https://discord.gg/ga2AWxWK – zain ul din Dec 24 '22 at 18:03
  • @xpt One possible cause of this issue is the router.get("/link/:id/*" route is being registered after the 404 error handling middleware. In this case, the 404 error handling middleware will catch all requests, including those that match the router.get("/link/:id/*" route.One possible cause of this issue is that the router.get("/link/:id/*" route is being registered after the 404 error handling middleware. In this case, the 404 error handling middleware will catch all requests, including those that match the router.get("/link/:id/*" route. – zain ul din Dec 24 '22 at 18:39
  • Thanks athena, I'm too green to JS world to be of any help. Yep, that url rule works, just that the `rest` is only `/abc/def`, not the full url param string. – xpt Dec 24 '22 at 19:09
  • @xpt no problem, I love to work with you if you want! – zain ul din Dec 24 '22 at 19:19