简体   繁体   中英

How to obtain the next route's path in an Express app

I am catching all traffic before passing it forward using:

app.all('*', function(req, res, next) {
    ... run before stuff, related to the next req.route.path
    next();
});

and I want to run some code before calling the next() function. in order for me to know the proper code I need to run, I have to identify what is the next request route path.

Debugging current req object (inside all('*',.. ) does not giving any information about the next request.route.path

How can I get the next method route.path before calling it?

Your help will be appreciated. Thank you.

Instead of trying to look ahead, why not explicitly set middleware for the routes that need it?

var middleware = function (req, res, next) {
  ..run your code in here
};

app.get('/users:user_id', middleware, function(req, res, next) {

}); 

You can get the next route by checking the route when the response in the middleware has fired the finish event:

app.all('*', function(req, res, next) {
  res.on('finish', function() {
    console.log('Next route: ', req.route.path);
  });
  next();
});

For a route defined like this:

app.get('/users/:user_id', function(req, res) {
  res.send('Hello');
});

You'll obtain the log:

$ Next route: '/users/:user_id'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM