【问题标题】:handler path in Nest.jsNest.js 中的处理程序路径
【发布时间】:2021-02-21 18:11:06
【问题描述】:

我有这个PATCH 请求:http://localhost:3000/tasks/566-344334-3321/status

使用该请求的处理程序:

@Patch('/:id/status')
updateTaskStatus() { // do stuff 
    return "got through";
}

我不了解 stem 部分背后的机制以及如何分配正确的处理程序来处理请求。

所以来自/566-344334-3321/status
id 部分是 /566-344334-3321,可以是任何值。
但是以/status 结尾的词干必须完全是/status
如果不是,则会出现"error": "Not Found"

这种行为背后的基本逻辑是什么?

【问题讨论】:

    标签: typescript express nestjs handler


    【解决方案1】:

    要获取id 参数,您需要使用@Param 装饰器将请求中的:id 分配给打字稿编号。

    根据NestJS documentation about Route Parameters,您应该按照以下方式编写updateTaskStatus 函数

    @Patch('/:id/status')
    updateTaskStatus(@Param('id') id: number) { 
        return `Got ${id} through`;
    }
    

    如果您的问题是将status 用作id 之类的动态值,则需要将相同的装饰器应用于您的参数

    @Patch('/:id/:status')
    updateTaskStatus(@Param('id') id: number, @Param('status') status: string) { 
        return `Got ${id} and ${status} through`;
    }
    

    NestJS 文档非常好和完整,不要犹豫阅读documentation about the controllers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      相关资源
      最近更新 更多