如何在Nest.js中使用查询参数?

问题描述 投票:1回答:1

我是Nest.js的新生。

我的代码如下

  @Get('findByFilter/:params')
  async findByFilter(@Query() query): Promise<Article[]> {

  }

我用postman来测试这个路由器

http://localhost:3000/article/findByFilter/bug?google=1&baidu=2

实际上,我可以得到查询结果{ google: '1', baidu: '2' }。但我不清楚为什么网址有一个字符串'bug'

如果我删除那个词就像

http://localhost:3000/article/findByFilter?google=1&baidu=2

然后邮递员将显示statusCode 404

实际上,我不需要bug这个词,如何定制路由器来实现我的目的地就像http://localhost:3000/article/findByFilter?google=1&baidu=2

这里的另一个问题是如何让多个路由器指向一个方法?

javascript node.js typescript express nestjs
1个回答
8
投票

你必须删除:params才能按预期工作:

@Get('findByFilter')
async findByFilter(@Query() query): Promise<Article[]> {
  // ...
}

:param语法用于路径参数并匹配路径上的任何字符串:

@Get('products/:id')
getProduct(@Param('id') id) {

匹配路线

localhost:3000/products/1
localhost:3000/products/2abc
// ...

Route wildcards

要将多个端点与同一方法匹配,可以使用路由通配符:

@Get('other|te*st')

会匹配

localhost:3000/other
localhost:3000/test
localhost:3000/te123st
// ...
© www.soinside.com 2019 - 2024. All rights reserved.