【问题标题】:Overlapping routes are not working in Koa.js重叠路由在 Koa.js 中不起作用
【发布时间】:2021-11-29 06:24:05
【问题描述】:

当我调用/my/abc/create 时,由于第一个入口点,我总是得到状态 400。 如何调用第二个端点?我不想更改入口点顺序。

var Router = require('koa-router');

var router = Router();


router.get('/my/:path/:id', (ctx) =>{
    if (isNaN(Number(cox.params.id))) { // if not numeric
        ctx.status = 400;
        return;
    }
    console.log('route id')
})
router.get('/my/:path/create', (ctx) =>{ 
    console.log('route create')
})

【问题讨论】:

  • 先注册创建路由。 I prefer not to change the entrypoint order。为什么?这是唯一的解决方案。
  • 哦,这是唯一的解决方案吗?我以为有办法……我不想改变顺序,因为我可能有更多的入口点,比如创建,所以我不想每次创建新的时候都关心订单
  • 我的错,绝对不是唯一的解决方案,但是如果ctx.params.id === 'create' 很难看,另一个解决方案需要检查您的第一条路线。
  • 是的,我也想过解决方案,但是如果我创建很多入口点,比如创建,代码会很乱。我想避免它
  • so I don't want to care about order every time I make new one。好吧,如果您不想关心订单,那么您不应该制作可以相互影响的路线。例如,create 路由可能应该是 POST,:id 路由可能应该只是 GET。通常,在 RESTful 设计中,URL 中没有像 create 这样的动词,这是通过请求是 POST 的事实推断出来的。

标签: javascript typescript koa koala koa-router


【解决方案1】:

就 REST 而言,您根本不会有 create 路由:

router.get('/my/:path/:id', (ctx) => /* get entity */)
router.post('/my/:path', (ctx) => /* create entity */)
router.patch('/my/:path/:id', (ctx) => /* update entity */)
router.delete('/my/:path/:id', (ctx) => /* delete entity */)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-23
    • 2020-02-05
    • 2016-07-11
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多