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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54958244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:48:28  来源:igfitidea点击:

How to use query parameters in Nest.js?

javascriptnode.jstypescriptexpressnestjs

提问by Eve

I am a freshman in Nest.js.

我是 Nest.js 的大一新生。

And my code as below

我的代码如下

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

  }

I have used postmanto test this router

我曾经postman测试过这个路由器

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

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'?

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

If I delete that word just like

如果我删除那个词就像

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

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

then the postman will shows statusCode 404.

然后邮递员将显示 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

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

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

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

回答by Kim Kern

You have to remove :paramsfor it to work as expected:

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

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


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

:param语法是路径参数和路径上的任何字符串相匹配:

@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
// ...

回答by Dmitry Grinko

we can use @Req()

我们可以使用@Req()

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

/nest?version=7

/nest?version=7

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

read more

阅读更多

回答by Hítallo Willian

You can use the @Reqdecorator, and use param object, see :

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

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