Skip to content

Commit

Permalink
Fix router prefix and index '/' route
Browse files Browse the repository at this point in the history
https://github.com/pillarjs/path-to-regexp/blob/master/History.md#200--2017-08-23
> Explicitly handle trailing delimiters instead of trimming them
(e.g. /test/ is now treated as /test/ instead of /test when matching)
  • Loading branch information
Sinewyk committed Apr 8, 2020
1 parent 5fcc2ed commit e047222
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
6 changes: 5 additions & 1 deletion lib/layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,11 @@ Layer.prototype.param = function (param, fn) {

Layer.prototype.setPrefix = function (prefix) {
if (this.path) {
this.path = prefix + this.path;
if (this.path !== '/' || this.opts.strict === true) {
this.path = prefix + this.path;
} else {
this.path = prefix;
}
this.paramNames = [];
this.regexp = pathToRegexp(this.path, this.paramNames, this.opts);
}
Expand Down
59 changes: 57 additions & 2 deletions test/lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -1107,7 +1107,7 @@ describe('Router', function () {
done();
}, error => done(error));
});

it('uses a same router middleware at given paths continuously - ZijianHe/koa-router#gh-244 gh-18', function (done) {
const app = new Koa();
const base = new Router({ prefix: '/api' });
Expand Down Expand Up @@ -1234,7 +1234,7 @@ describe('Router', function () {
});
url.should.equal('/programming/how%20to%20node');
done();

});

it('generates URL for given route name within embedded routers', function (done) {
Expand Down Expand Up @@ -1852,6 +1852,61 @@ describe('Router', function () {
});
}
}

it(`prefix and '/' route behavior`, function(done) {
var app = new Koa();
var router = new Router({
strict: false,
prefix: '/foo'
});

var strictRouter = new Router({
strict: true,
prefix: '/bar'
})

router.get('/', function(ctx) {
ctx.body = '';
});

strictRouter.get('/', function(ctx) {
ctx.body = '';
});

app.use(router.routes());
app.use(strictRouter.routes());

var server = http.createServer(app.callback());

request(server)
.get('/foo')
.expect(200)
.end(function (err) {
if (err) return done(err);

request(server)
.get('/foo/')
.expect(200)
.end(function (err) {
if (err) return done(err);

request(server)
.get('/bar')
.expect(404)
.end(function (err) {
if (err) return done(err);

request(server)
.get('/bar/')
.expect(200)
.end(function (err) {
if (err) return done(err);
done();
});
});
});
});
})
});

describe('Static Router#url()', function () {
Expand Down

0 comments on commit e047222

Please sign in to comment.