From 6df224c9390722afb4acd127a0c940312ec48b00 Mon Sep 17 00:00:00 2001 From: Mike Tunnicliffe Date: Wed, 24 Feb 2016 14:16:54 +0000 Subject: [PATCH] Make req.route an object saving route and baseUrl When using an error handler you have access to req.route which describes the most recently matched route. However, some other informaiton (like req.baseUrl) gets changed before the error handler runs. This commit changes req.route to an object that also contains the req.baseUrl before it gets changed. Since the actual route object is not scoped to the current event, this commit instead uses a new object to store the baseUrl but sets the __proto__ to the route object so that all its properties are also available. --- index.js | 3 ++- lib/route.js | 3 ++- test/router.js | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index b488e585..a10ea337 100644 --- a/index.js +++ b/index.js @@ -271,7 +271,8 @@ Router.prototype.handle = function handle(req, res, callback) { // store route for dispatch on change if (route) { - req.route = route + req.route = req.route || { __proto__: route } + req.route.baseUrl = req.baseUrl; } // Capture one-time layer values diff --git a/lib/route.js b/lib/route.js index 8b67f2de..713be35a 100644 --- a/lib/route.js +++ b/lib/route.js @@ -104,7 +104,8 @@ Route.prototype.dispatch = function dispatch(req, res, done) { method = 'get' } - req.route = this + req.route = req.route || { __proto__: this } + req.route.baseUrl = req.baseUrl; next() diff --git a/test/router.js b/test/router.js index 046bd322..ac2af582 100644 --- a/test/router.js +++ b/test/router.js @@ -411,6 +411,23 @@ describe('Router', function () { .expect('x-is-route', 'true') .expect(200, done) }) + + it('should have the correct baseUrl', function (done) { + var router = new Router() + var inner = new Router() + var server = createServer(router) + + inner[method]('/bar', function handle(req, res) { + res.setHeader('x-route-base', String(req.route.baseUrl === '/foo')) + res.end() + }) + router.use('/foo', inner); + + request(server) + [method]('/foo/bar') + .expect('x-route-base', 'true') + .expect(200, done) + }) }) }) })