Home > Software engineering >  In Node/Express, how to fetch the current route handler?
In Node/Express, how to fetch the current route handler?

Time:10-21

How do I fetch the syntax/name of the current route handler, ignoring the current specific param values?

e.g.:

app.get('/users/:id', (req, res) => {
    let route = ?
    console.log(route) // --> "/users/:id"
})

(Question 2 - can I do this in a middleware function?)

CodePudding user response:

The correct answer is req.route.path

e.g.

1. Call directly from main file (app.js / index.js):

app.get('/admin/:foo/:bar/:baz', async (req, res) => {
    console.log(req.originalUrl);
    console.log(req.url);
    console.log(req.path);
    console.log(req.route.path);  // this one is your answer
    console.log(req.baseUrl);
    console.log(req.hostname);
    res.sendStatus(200);
});

API call:

http://localhost:3000/admin/a/b/c

Output

/admin/a/b/c (originalUrl)
/admin/a/b/c (url)
/admin/a/b/c (path)
/admin/:foo/:bar/:baz (route.path)
<nothing> (baseUrl)
localhost (hostname)


2. Call from a module:

app.js

const express = require('express');
const app = express();

...

const users = require('./users');
app.use('/api/users', users);

users.js

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

...

router.get('/admin/:foo/:bar/:baz', async (req, res) => {
    console.log(req.originalUrl);
    console.log(req.url);
    console.log(req.path);
    console.log(req.route.path);  // this one is your answer
    console.log(req.baseUrl);
    console.log(req.hostname);
    res.sendStatus(200);
});

API call:

http://localhost:3000/admin/a/b/c

Output

/api/users/admin/a/b/c (originalUrl)
/admin/a/b/c (url)
/admin/a/b/c (path)
/admin/:foo/:bar/:baz (route.path)
/api/users (baseUrl)
localhost (hostname)

CodePudding user response:

You can see below example for information about req object that you get.

/users can be obtained from req.baseUrl and :id can be obtained from req.params.id

app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl   req.path) // '/admin/new' (full path without query string)
  next()
})

  • Related