Skip to content

Commit ac7416c

Browse files
authored
fix: koa router trailer slash (#1114)
1 parent 5e5a8c0 commit ac7416c

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/driver/koa/KoaDriver.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,13 @@ export class KoaDriver extends BaseDriver {
129129
const afterMiddlewares = this.prepareMiddlewares(uses.filter(use => use.afterAction));
130130

131131
// prepare route and route handler function
132-
const route = ActionMetadata.appendBaseRoute(this.routePrefix, actionMetadata.fullRoute);
132+
let route = ActionMetadata.appendBaseRoute(this.routePrefix, actionMetadata.fullRoute);
133+
134+
// @koa/router is strict about trailing slashes, allow accessing routes without them
135+
if (typeof route === 'string' && route.length > 1 && route.endsWith('/')) {
136+
route = route.substring(0, route.length - 1);
137+
}
138+
133139
const routeHandler = (context: any, next: () => Promise<any>) => {
134140
const options: Action = { request: context.request, response: context.response, context, next };
135141
return executeCallback(options);
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { Server as HttpServer } from 'http';
2+
import HttpStatusCodes from 'http-status-codes';
3+
import { Controller } from '../../src/decorator/Controller';
4+
import { Get } from '../../src/decorator/Get';
5+
import { createKoaServer, getMetadataArgsStorage } from '../../src/index';
6+
import { axios } from '../utilities/axios';
7+
import DoneCallback = jest.DoneCallback;
8+
9+
describe(``, () => {
10+
let koaServer: HttpServer;
11+
12+
describe('koa trailing slashes', () => {
13+
beforeEach((done: DoneCallback) => {
14+
getMetadataArgsStorage().reset();
15+
16+
@Controller('/posts')
17+
class PostController {
18+
@Get('/')
19+
getAll(): string {
20+
return '<html><body>All posts</body></html>';
21+
}
22+
}
23+
24+
koaServer = createKoaServer().listen(3001, done);
25+
});
26+
27+
afterEach((done: DoneCallback) => {
28+
koaServer.close(done);
29+
});
30+
31+
it('get should respond to request without a traling slash', async () => {
32+
expect.assertions(3);
33+
const response = await axios.get('/posts');
34+
expect(response.status).toEqual(HttpStatusCodes.OK);
35+
expect(response.headers['content-type']).toEqual('text/html; charset=utf-8');
36+
expect(response.data).toEqual('<html><body>All posts</body></html>');
37+
});
38+
39+
it('get should respond to request with a traling slash', async () => {
40+
expect.assertions(3);
41+
const response = await axios.get('/posts/');
42+
expect(response.status).toEqual(HttpStatusCodes.OK);
43+
expect(response.headers['content-type']).toEqual('text/html; charset=utf-8');
44+
expect(response.data).toEqual('<html><body>All posts</body></html>');
45+
});
46+
});
47+
});

0 commit comments

Comments
 (0)