Using two routers, the next bug of regular routing
1stgg opened this issue · comments
1stgg commented
node.js version: v14.17.6
npm/yarn and version: 1.22.11
@koa/router
version: 10.1.1
koa
version: 2.13.4
Code sample:
let app = new (require("koa"))()
let routerA = new (require("koa-router"))()
let routerB = new (require("koa-router"))()
routerA.get('/test/(.*?)', async (ctx,next) => {
console.log('/test/(.*?)');
await next()
})
routerB.get('/test/child', async (ctx) => {
ctx.body = '/test/child';
})
app.use(routerA.routes())
app.use(routerB.routes())
app.listen(3000, () => {
console.log('应用已经启动,http://localhost:3000');
})
Expected Behavior:
GET http://localhost:3000/test/child
response.body = '/test/child'
Actual Behavior:
GET http://localhost:3000/test/child
response 404 Not Found
Additional steps, HTTP request details, or to reproduce the behavior or a test case:
1stgg commented
Normal if regular routing is not used
routerA.get('/test/child', async (ctx,next) => {
console.log('/test/(.*?)');
await next()
})
Yorn Qiu commented
Normal if regular routing is not used
routerA.get('/test/child', async (ctx,next) => { console.log('/test/(.*?)'); await next() })
对于/test/child,两个路由都匹配上了,然后依次执行了对应的handler,就产生了错误。
因为这个koa-router的匹配规则就是匹配上的都会执行。
实际上早有人提出了问题并且发起了PR来解决这个问题,但是这个库貌似挺久没维护了。。。
目前只能换一种route的写法,让他不会匹配上多个。
Dimitry Ivanov commented
The same thing:
const Koa = require('koa');
const Router = require('@koa/router');
const app = new Koa();
const router1 = new Router();
const router2 = new Router();
router1.get('/:id', async (ctx, next) => {
console.log('1 >>', ctx.params.id);
await next();
});
router2.get('/:id', async (ctx, next) => {
console.log('2 >>', ctx.params);
ctx.body = ctx.params;
});
app
.use(router1.routes())
.use(router2.routes());
app.listen(3002);
console.log('KOA is on 3002');
on curl localhost:3002/12
will print:
KOA is on 3002
1 >> 12
2 >> { id: ':id' }
created pr for this issue: #160
Dimitry Ivanov commented
@1stgg it can be solved by redefined routerPath
:
let app = new (require("koa"))()
let routerA = new (require("koa-router"))()
let routerB = new (require("koa-router"))()
routerA.get('/test/(.*?)', async (ctx,next) => {
console.log('/test/(.*?)');
ctx.routerPath = `/test/${ctx.params[0]}`;
await next()
})
routerB.get('/test/child', async (ctx) => {
ctx.body = '/test/child';
})
app.use(routerA.routes())
app.use(routerB.routes())
app.listen(3000, () => {
console.log('应用已经启动,http://localhost:3000');
})
Imed Jaberi commented
Fixed through this PR (#160)