繁体   English   中英

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

[英]How to use query parameters in Nest.js?

我是 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' } 但我不清楚为什么 url 有一个字符串'bug'

如果我删除那个词就像

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

然后 postman 将显示 statusCode 404

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

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

查询参数

您必须删除: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
// ...

路由通配符

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

@Get('other|te*st')

会匹配

localhost:3000/other
localhost:3000/test
localhost:3000/te123st
// ...

我们可以使用@Req()

@Get(':framework')
getData(@Req() request: Request): Object {
    return {...request.params, ...request.query};
}

/nest?version=7

{
    "framework": "nest",
    "version": "7"
}

阅读更多

如果您将参数作为部分或网址: /articles/${articleId}/details ,您将使用 @Param

@Get('/articles/:ARTICLE_ID/details')
async getDetails(
    @Param('ARTICLE_ID') articleId: string
)

如果您想提供查询参数/article/findByFilter/bug? google=1&baidu=2 ,你可以使用

@Get('/article/findByFilter/bug?')
async find(
    @Query('google') google: number,
    @Query('baidu') baidu: number,
)

您可以使用@Req装饰器,并使用 param 对象,请参阅:

@Get()
  findAll(
    @Req() req: Request
  ): Promise<any[]> {
    console.log(req.query);
    // another code ....
  }

为了更好地解释,我用数字转换器 class 写了一个分页示例:

class QueryDto {
    @Type(() => Number)
    @IsInt()
    public readonly page: number;

    @Type(() => Number)
    @IsInt()
    public readonly take: number;
}

@Injectable()
class QueryTransformPipe implements PipeTransform {
    async transform(value: QueryRequestDto, { metatype }: ArgumentMetadata) {
        if (!metatype) {
            return value;
        }

        return plainToInstance(metatype, value);
    }
}


@Controller()
class YourController {
    @Get()
    // also you can use it with pipe decorator
    // @UsePipes(new QueryTransformPipe())
    public async getData(@Query(new QueryTransformPipe()) query?: QueryRequestDto): Promise<any[]> {
        // here you get instanceof QueryTransformPipe
        // and typeof query.page === 'number' && typeof query.take === 'number'
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM