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
How to use query parameters in Nest.js?
提问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 postman
to 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 :params
for it to work as expected:
您必须删除:params
它才能按预期工作:
@Get('findByFilter')
async findByFilter(@Query() query): Promise<Article[]> {
// ...
}
The :param
syntax 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
回答by Hítallo Willian
You can use the @Req
decorator, and use param object, see :
您可以使用@Req
装饰器,并使用 param 对象,请参阅:
@Get()
findAll(
@Req() req: Request
): Promise<any[]> {
console.log(req.query);
// another code ....
}