I managed to match everything under /api/
:
import Koa from 'koa';
import Router from '@koa/router';
const app = new Koa();
const apiRouter = new Router();
const catchAll = new Router();
catchAll.get('/(.*)', async (ctx, next) => {
console.log("Here is some middleware");
console.log('/' + ctx.params[0]);
await next();
console.log(ctx.body)
}, async (ctx, next) => {
ctx.body = 'catch all with URL ' + ctx.url;
ctx.status = 201;
await next();
});
apiRouter.use('/api', catchAll.routes());
app.use(apiRouter.routes());
app.listen(3000);
This does not match /api
without a trailing slash, though.
I found a simpler way to achieve the same. However, it does not use the use
method of the router instance:
import Koa from 'koa';
import Router from '@koa/router';
const app = new Koa();
const apiRouter = new Router();
apiRouter.get('/api/(.*)', async (ctx, next) => {
console.log("Here is some middleware");
console.log('/' + ctx.params[0]);
await next();
console.log(ctx.body)
}, async (ctx, next) => {
ctx.body = 'catch all with URL ' + ctx.url;
ctx.status = 201;
await next();
});
app.use(apiRouter.routes());
app.listen(3000);
Notice how the second way's '/api/.*'
is the first way's '/api'
+ '/(.*)'
.
And apparently, the use
of the router instance performs concatenation for the get
paths (and similarly for post
etc), so, if you used (.*)
without leading slash for catchAll.get
in the first way above, it would try to just concatenate it to /api(.*)
, which then would match /api2
and the likes.