How do I "capture" the full route of an http call with express router?

Asked

Viewed 55 times

-2

I’m using the express.router nesting my route into several "router.use()". It is possible to take the final route via console?

ex:

const routes = Router();
const v1Router = Router();
const enggajadoresRouter = Router();

routes.use('/v1', V1Router);
v1Router.use('/usuarios', UsuariosRouter);
UsuarioRouter.post('/', usuariosControllers.create);

in this case my post route will be localhost:3000/v1/users/

I need a medium in which I can get the value: '/v1/users/'

1 answer

4

To get the request path

Use the property path. Of documentation:

// https://example.com/users?sort=desc

console.dir(req.path);
//=> '/users'

To get the full URL

  1. Utilise req.protocol to obtain the requisition protocol, such as http or https;
  2. Utilise req.get('host') to obtain the host of the requisition;
  3. The path can be obtained with req.originalUrl. Note that the property originalUrl also includes the query Parameters, then depending on the purpose may not be what you want.

So, to mount the full URL, you can concatenate the parts to mount the full string. So:

// https://example.com/users?sort=desc

const fullURL = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
console.log(fullURL);
//=> https://example.com/users?sort=desc

Inspired in this answer Stack Overflow in English.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.