3

I have a requirement to get the exact path of the URL for use in another middleware for resusability purposes. It should return the url without the path parameter converted to specific value, and without the query parameter.

Eg: if the user enters https://localhost:3000/path1/4/path2, where /4 is defined as /:id in my defined path, then the extracted path should be /path1/:id/path2.

So far, the only useful ways I have found are:

  1. using req.originalUrl => would return /path1/4/path2
  2. using req.baseUrl + req.path => would return /path/4/path2 as well, same as above
  3. using req.route.path => would actually return the required output /path1/:id/path2, but unfortunately does not work when nesting routes with express router as it only returns the nested path.

For example and reference, please have a look at the below snippet:

const express = require("express");

const routes = express.Router();
routes.get("/path2", async (req, res, next) => {

    //assuming a URL of "https://localhost:3000/path1/12/path2?someparam=5"
    //desired output: "/path1/:id/path2"

    console.log(req.originalUrl) // returns "/path1/12/path2"
    console.log(req.baseUrl + req.path); // returns "/path1/12/path2"
    console.log(req.route.path); //returns only "/path2"

});

app.use("/path1/:id", routes); //using the router to nest paths makes req.route.path unusable

I have referred to the answers in this, but they don't suit my exact requirements. Any help would be appreciated. Thanks

lanxion
  • 1,350
  • 1
  • 7
  • 20
  • Anyone trying to get the path, It's not possible directly but express can be patched to add that to req object. I ended up making this package [px5](https://www.npmjs.com/package/px5) to do it. – TubbyStubby Feb 05 '23 at 21:12

0 Answers0