How to get the exact URL path defined by me in express middleware without path parameter values and query parameters?

Viewed 283

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

1 Answers

you tried using req.params with some js string functions ? i did not understand what you really need in return can you please share more code + more details so i can help more efficiently and thanks

Related