Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Does anyone know if it's possible to get the path used to trigger the route?

For example, let's say I have this:

app.get('/user/:id', function(req, res) {});

With the following simple middleware being used

function(req, res, next) {
     req.?
});

I'd want to be able to get /user/:id within the middleware, this is not req.url.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
334 views
Welcome To Ask or Share your Answers For Others

1 Answer

What you want is req.route.path.

For example:

app.get('/user/:id?', function(req, res){
  console.log(req.route);
});

// outputs something like

{ path: '/user/:id?',
  method: 'get',
  callbacks: [ [Function] ],
  keys: [ { name: 'id', optional: true } ],
  regexp: /^/user(?:/([^/]+?))?/?$/i,
  params: [ id: '12' ] }

http://expressjs.com/api.html#req.route


EDIT:

As explained in the comments, getting req.route in a middleware is difficult/hacky. The router middleware is the one that populates the req.route object, and it probably is in a lower level than the middleware you're developing.

This way, getting req.route is only possible if you hook into the router middleware to parse the req for you before it's executed by Express itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...