I have a very simple routing code using @koa/router:
import Koa from 'koa';
import Router from '@koa/router';
const app = new Koa();
const router = new Router();
router.use('/api', (ctx, next) => {
ctx.body = 'catch all with use';
ctx.status = 201;
next();
});
app.listen(3000);
However accessing the path http://localhost:3000/api returns 404. So, what is the exact use of use method of the router?
I wish to send all the request starting with /api prefix to a custom middleware which itself could be a @koa/router middleware or any other Koa middleware.
I managed to match everything under
/api/:This does not match
/apiwithout a trailing slash, though.I found a simpler way to achieve the same. However, it does not use the
usemethod of the router instance:Notice how the second way's
'/api/.*'is the first way's'/api'+'/(.*)'.And apparently, the
useof the router instance performs concatenation for thegetpaths (and similarly forpostetc), so, if you used(.*)without leading slash forcatchAll.getin the first way above, it would try to just concatenate it to/api(.*), which then would match/api2and the likes.