diff --git a/lib/router.js b/lib/router.js index 947f250..8d7aa31 100644 --- a/lib/router.js +++ b/lib/router.js @@ -310,7 +310,7 @@ Router.prototype.routes = Router.prototype.middleware = function () { if (matched.pathAndMethod.length) { i = matched.pathAndMethod.length; - while (i--) { + while (matched.route && i--) { layer = matched.pathAndMethod[i]; ii = layer.stack.length; this.captures = layer.captures(path, this.captures); @@ -589,7 +589,8 @@ Router.prototype.match = function (path, method) { var layer; var matched = { path: [], - pathAndMethod: [] + pathAndMethod: [], + route: false }; for (var len = layers.length, i = 0; i < len; i++) { @@ -600,8 +601,9 @@ Router.prototype.match = function (path, method) { if (layer.match(path)) { matched.path.push(layer); - if (!layer.methods.length || ~layer.methods.indexOf(method)) { + if (layer.methods.length === 0 || ~layer.methods.indexOf(method)) { matched.pathAndMethod.push(layer); + if (layer.methods.length) matched.route = true; } } } diff --git a/test/lib/router.js b/test/lib/router.js index 277994a..dbdd6c4 100644 --- a/test/lib/router.js +++ b/test/lib/router.js @@ -57,6 +57,33 @@ describe('Router', function() { }); }); + it('matches middleware only if route was matched (gh-182)', function (done) { + var app = koa(); + var router = new Router(); + var otherRouter = new Router(); + + router.use(function *(next) { + this.body = { bar: 'baz' }; + yield next; + }); + + otherRouter.get('/bar', function *(next) { + this.body = this.body || { foo: 'bar' }; + }); + + app.use(router.routes()).use(otherRouter.routes()); + + request(http.createServer(app.callback())) + .get('/bar') + .expect(200) + .end(function (err, res) { + if (err) return done(err); + expect(res.body).to.have.property('foo', 'bar'); + expect(res.body).to.not.have.property('bar'); + done(); + }) + }); + it('matches first to last', function (done) { var app = koa(); var router = new Router();