Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain matched route pattern in express JS?

I want my logger middleware to log each matched route when response is sent. But there may be any number of nested subroutes. Let's suppose I have this:

var app = express();
var router = express.Router();

app.use(function myLogger(req, res, next)
{
    res.send = function()
    {
        //Here I want to get matched route like this: '/router/smth/:id'
        //How can I do this?
    });
}

app.use('/router', router);

router.get('/smth/:id', function(req, res, next)
{
  res.send(response);
});

Is it possible?

like image 232
Andrey Kon Avatar asked Dec 09 '14 18:12

Andrey Kon


People also ask

How is it possible to create Chainable route handlers for a route path in Express JS?

By using app. route() method, we can create chainable route handlers for a route path in Express.

What are the methods which are used by Express to route request?

Express supports methods that correspond to all HTTP request methods: get , post , and so on. For a full list, see app.METHOD. There is a special routing method, app.all() , used to load middleware functions at a path for all HTTP request methods.

How the dynamic routing is working in Expressjs give an example?

To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. var express = require('express'); var app = express(); app. get('/:id', function(req, res){ res.

Which function of an Express app can be used to configure an HTTP GET route?

Use app object to define different routes of your application. The app object includes get(), post(), put() and delete() methods to define routes for HTTP GET, POST, PUT and DELETE requests respectively.


1 Answers

Because app-level middleware has no knowledge of routes, this is impossible. However, if you use your logger middleware as route middleware like:

router.get('/smith/:id', logger, function (req, res) { ... });

You can use a combination of two parameters on the request object:

req.route.path => '/smth/:id'
req.originalUrl => '/router/smth/123'

I'll leave it up to you how you want to combine both into one string.

like image 180
srquinn Avatar answered Sep 20 '22 06:09

srquinn