【发布时间】:2026-02-16 23:40:01
【问题描述】:
我希望能够从我的查询参数中获取车牌,但无论我以何种方式编写代码,它似乎都不起作用,所以我很困惑为什么它不起作用。
这是预期的行为:使用以下 GET 请求时:http://localhost:3978/licenseplate/getleasingcompany?licenseplate=1-WMW-478
我想提取车牌参数。
这是我当前的代码:
@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.licenseplate 是undefined)
另一个选项可以在 * 解释 here 中找到,其中 Kim 使用了路径参数。这确实对我有用,但不幸的是,这不是我的程序可以使用的行为。
谁能解释我做错了什么?谢谢!
编辑 1:在几个 cmets 之后,我将我的包更新到版本 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] 作为结果。
【问题讨论】:
-
@Query()是从哪里导入的?是来自@nestjs/graphql的偶然吗?你的 Nest 通用包、核心包和平台包在同一个版本上吗? -
都是从Common导入的。
import { Controller, Get, Body, HttpException, Post, Query } from "@nestjs/common";。除了typeORM,都是6.7.2版本,typeORM是7.0.0 -
你有这个的复制品吗?
-
很遗憾,由于这些文件与我的工作相关,我无法共享这些文件。然而,我找到了一个“解决方案”,我将在下面的答案中分享。
标签: node.js typescript nestjs