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?
By using app. route() method, we can create chainable route handlers for a route path in Express.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With