Home > database >  How to get path of different express route
How to get path of different express route

Time:11-20

Lets say I have the following routes in my express app:

router.get('/register', registrationController.register);

router.get('/confirm', registrationController.confirm);

In some service I would like to retrieve the absolute url of the confirm route.

Instead of doing something like this:

const url = req.protocol   '://'   req.get('host')   '/confirm'

Is there an option to retrieve routes in some way like this:

const express = require('express');
const router = express.Router();

const confirmRoute = router.confirm;

// Do something with the route name instead of typing it statically as a string

What can I do differently without installing another dependency?

CodePudding user response:

Define a constant that you can use in multiple places.

const confirmRoute = "/confirm";

Then, you can use that in multiple places. If those places are in separate files, then you can either export it from the file where it was declared and import in the other. Or, you can create a shared constants file and export it from there and both other files that want to use it can import it from that shared file.

Alternately, you don't even have to expose the route itself. You can keep that private to the file where they route is defined and then export and function that either retrieves the route path or just executes the redirect for you.

  • Related