Home > other >  Node express to catch all optional parameters after url-path-params
Node express to catch all optional parameters after url-path-params

Time:12-25

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}` : ""
...

CodePudding user response:

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}`);
  // ...
};
  • Related