
[英]How to change query parameters serialization using nestjs/swagger?
[英]How to get parameters out of Query in NestJS
我希望能够从我的查询参数中获取车牌,但无论我以何种方式编写代码,它似乎都不起作用,所以我很困惑为什么它不起作用。
这是预期的行为:使用以下 GET 请求时: http://localhost:3978/licenseplate/getleasingcompany?licenseplate=1-WMW-478
我想提取 licenseplate 参数。
这是我当前的代码:
@Get('getleasingcompany')
async getLeasingCompany(@Query('licenseplate') licenseplate: string) {
console.log(licenseplate);
}
在licenseplate
中尝试时,这会将车牌记录为undefined
。
我还尝试了此代码的变体,例如:
@Get('getleasingcompany')
async getLeasingCompany(@Query() query) {
console.log(query);
}
此记录为[Function: getQuery]
的query
,我不知道如何处理( query.licenseplate
undefined
)
在此处的 Stackoverflow 解释中可以找到另一个选项,其中 Kim 使用路径参数。 这确实对我有用,但不幸的是,这不是我的程序可以使用的行为。
谁能解释我做错了什么? 谢谢!
编辑 1:经过一些评论,我将我的包更新到版本 7.1.2,但无济于事。 将query
返回到 postman 给出以下 output:
function getQuery() {
// always return a string, because this is the raw query string.
// if the queryParser plugin is used, req.query will provide an empty
// object fallback.
return this.getUrl().query || '';
}
编辑 2:尝试通过如下导入Request
走 Express 路线: import { Request } from "express";
. 代码现在看起来像这样:
@Get('getleasingcompany')
async getLeasingCompany(@Req() request: Request) {
console.log(request);
}
此日志的一部分确实向我显示查询保存了变量:
originalUrl: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
_parsedUrl:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?licenseplate=1-WMW-478',
query: 'licenseplate=1-WMW-478',
pathname: '/licenseplate/getleasingcompany',
path: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
href: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478',
_raw: '/licenseplate/getleasingcompany?licenseplate=1-WMW-478' },
但是,在记录request.query
时,我仍然得到[Function: GetQuery]
作为结果。
您的代码中没有任何问题。 在 Nest v7 上使用以下 controller 和 curl 我得到了你所期望的
import { Controller, Get, Query } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(@Query() query: Record<string, any>): string {
console.log(query);
return this.appService.getHello();
}
}
curl http://localhost:3000/\?queryparam\=something
[Nest] 46471 - 06/02/2020, 2:55:11 PM [NestFactory] Starting Nest application...
[Nest] 46471 - 06/02/2020, 2:55:11 PM [InstanceLoader] AppModule dependencies initialized +12ms
[Nest] 46471 - 06/02/2020, 2:55:11 PM [RoutesResolver] AppController {}: +15ms
[Nest] 46471 - 06/02/2020, 2:55:11 PM [RouterExplorer] Mapped {, GET} route +9ms
[Nest] 46471 - 06/02/2020, 2:55:11 PM [NestApplication] Nest application successfully started +9ms
{ queryparam: 'something' }
我唯一的猜测是一些不匹配的 Nest 版本
我还没有找到程序没有按预期工作的原因,但是我只是通过启动一个新的 Nest 项目来解决这个问题。 当我注意到这个项目确实按预期工作时,我复制了除 package.json 之外的所有文件,并一一重新安装了所有必要的依赖项。 我只删除了 1 个依赖项, restify
,我最终不需要。 它可以与 package 一起使用,所以这不是问题。
由于这些发现,我想这一定是版本控制问题,尽管我仍然不确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.