我是 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
这里还有一个问题是如何让多个router指向一个方法?
最佳答案
查询参数
您必须删除 :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
// ...
关于javascript - 如何在 Nest.js 中使用查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54958244/