首页 > 解决方案 > 如何从 NestJS 中的 Query 中获取参数

问题描述

我希望能够从我的查询参数中获取车牌,但无论我以何种方式编写代码,它似乎都不起作用,所以我很困惑为什么它不起作用。

这是预期的行为:使用以下 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);
}

这记录query[Function: getQuery],我不知道如何处理(query.licenseplateundefined

在此处的 Stackoverflow 解释中可以找到另一个选项,其中 Kim 使用路径参数。这确实对我有用,但不幸的是,这不是我的程序可以使用的行为。

谁能解释我做错了什么?谢谢!

编辑 1:经过一些评论,我将我的包更新到版本 7.1.2,但无济于事。返回query给邮递员会给出以下输出:

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]结果。

标签: node.jstypescriptnestjs

解决方案


您的代码中没有任何问题。在 Nest v7 上使用以下控制器和 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 版本


推荐阅读