How to use query parameters in Nest.js?

会有一股神秘感。 提交于 2020-06-14 04:16:29

问题


I am a freshman in Nest.js.

And my code as below

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

  }

I have used postman to test this router

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

Actually, I can get the query result { google: '1', baidu: '2' }. But I'm not clear why the url has a string 'bug'?

If I delete that word just like

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

then the postman will shows statusCode 404.

Actually, I don't need the word bug, how to custom the router to realize my destination just like http://localhost:3000/article/findByFilter?google=1&baidu=2

Here's another question is how to make mutiple router point to one method?


回答1:


You have to remove :params for it to work as expected:

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

The :param syntax is for path parameters and matches any string on a path:

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

matches the routes

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

Route wildcards

To match multiple endpoints to the same method you can use route wildcards:

@Get('other|te*st')

will match

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



回答2:


we can use @Req()

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

/nest?version=7

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

read more




回答3:


You can use the @Req decorator, and use param object, see :

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


来源:https://stackoverflow.com/questions/54958244/how-to-use-query-parameters-in-nest-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!