TransWikia.com

How can i get the name of this JSON or get the path from NodeJS Express Router?

Stack Overflow Asked by Carlos Tinnelly on December 30, 2021

I’m trying to add the named routers feature to the express router for NodeJS (It’s a practice, i don’t want to donwload any other package), i’ve made it successfully, but just left one thing… the path, i mean, if i’ve got a route like:

index.js

const express = require('express');
const app = express();
app.use(require('./routes'));

routes/index.js

const express = require('express');
const expressRouter = express.Router();
const router = require("./namedRoutes")(expressRouter); // <- This is my own named router
const ViewsController  = require('../app/controllers/ViewsController');

router.get("/", ViewsController.loadHome).setName("home");
router.get("/fromHome", ViewsController.loadHome).setName("fromHome");

module.exports = router;

I can get the route name from my helper (handlebars) using:

{{ route "home" }} or {{ route "fromHome" }}

And it returns me:

localhost:3000/ or localhost:3000/fromHome

But when i try to prepend a path using this syntax on mi index.js

app.use("/other/path", require('./routes'));

My named routes will return me localhost:3000/ or localhost:3000/fromHome again without the path.

Doing test in my route helper i saw that i can get all the routes registered from the request object, this is an example of just one object route registered (These routes objects come inside of an array that is in req.app._router.stack):

Layer {
    handle: [Function: router] {
      params: {},
      _params: [],
      caseSensitive: undefined,
      mergeParams: undefined,
      strict: undefined,
      stack: [Array],
      _get: [Function],
      _post: [Function],
      _put: [Function],
      _delete: [Function],
      get: [Function],
      post: [Function],
      put: [Function],
      delete: [Function],
      setName: [Function],
      lastRouteAdded: '/fromOthers',
      names: [Array]
    },
    name: 'router',
    params: undefined,
    path: undefined,
    keys: [],
    regexp: /^/other/path/?(?=/|$)/i { fast_star: false, fast_slash: false },
    route: undefined
  }

As you can see, the path is undefined, but if you see, there’s a property called:

regexp: /^/other/path/?(?=/|$)/i { fast_star: false, fast_slash: false }

This is a regexp that contains the path, so if i could get that regexp i could get the path, but it seems to be that it’s no way to get it, if i try to do this (Supossing that the var routeInstance contains this JSON object):

const path = routeInstance.regexp;
console.log(path);

I get this:

/^/other/path/?(?=/|$)/i { fast_star: false, fast_slash: false }

But now i can’t get that regexp, if i do this:

console.log(Object.keys(path));

I get this:

[ 'fast_star', 'fast_slash' ]

As you can see, now there isn’t the regexp, and if i do this:

console.log(Object.keys(routeInstance));

(Remember that the var routeInstance contains the Layer object) I get this:

[
  'handle', 'name',
  'params', 'path',
  'keys',   'regexp',
  'route'
]

So, how can i get that regexp? Or how can i get that path if there’s other way to obtain it?

Note:

I know that app.use("/other/path", require('./routes')); allows you to put an regexp or array instead of a static path string, so my idea is that the route helper returns the most obvious route based on the past regexp.

I appreciate your response!!!

One Answer

Ok i've solved it, i can get that regexp doing this:

const regexpPath = routerInstance.regexp.toString();

It seems that the JSON Object is discarded and just return the regexp string.

So now i can get the path with this:

// Search all ocurrences of type /some (Returns an array)
const pathOcurrences = regexpPath.match(//[A-Za-z0-9]+/igm);

// Remove the last element 'cause it will still bring me the / i of the regexp
pathOcurrences.pop();

// Join the ocurrences
const path =  pathOcurrences.join("");

Obviously it will fails for a regexp that is not a path, but that's right, you're trying to get the path from a regexp, you can't so it works ^-^

Answered by Carlos Tinnelly on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP