nestjs - 无法使 @Get('id') 在 NestJS 教程中工作
问题描述
所以我正在关注本教程,并逐字逐句地遵循它:
https://medium.com/@kaushiksamanta23/nest-js-tutorial-series-part-1-introduction-setup-c87ba810ea9e
所以我的服务文件中有这个:
getCourse(courseId): Promise<any> {
let id = Number(courseId);
return new Promise(resolve => {
const course = this.courses.find(course => course.id === id);
if (!course) {
throw new HttpException('Course does not exist', 404)
}
resolve(course);
});
}
这在我的控制器中,就像在教程中一样,除了日志:
@Get(':courseId')
async getCourse(@Param('courseId') courseId) {
console.log(courseId)
const course = await this.coursesService.getCourse(courseId);
return course;
}
在邮递员中,当调用http://localhost:3000/courses/courseId=3时,我收到“消息”:“课程不存在”
日志清楚地显示了问题:
{ courseId: 'courseId=3' }
因此,当我尝试http://localhost:3000/courses/3时,它可以工作,但这不是正确的方法。
我在这里迷路了,我的代码与教程中的代码相同,我认为@Param('courseId') 的全部目的是将字符串'courseId'识别为键并获取'='之后的任何值网址。如果是这样,为什么我会收到“courseId=3”?当然,我不应该手动解析字符串。
解决方案
您将 URL 参数与查询参数混淆了。在 URL 中,您可以拥有根据路由处理程序以不同方式解析的参数。在这种情况下,您的 URL 表示您有一个 base ,courses
然后是一个 name 的 url 参数courseId
。当您发出请求时,URL 看起来像http://localhost/courses/3
(3 是courseId
),然后您会得到 id like req.param['courseId]
。如果您想使用更像的 URL,http://localhost/courses/?courseId=3
则需要使用@Query()
instead 来获取查询参数(这将映射到req.query
而不是req.param
)
推荐阅读
- jquery - 在取消选中复选框时淡出相应的图像
- html - 如何调整图像大小以保持比例
- vb.net - OpenFileDialog - png 文件不显示在对话框中
- c++ - Leetcode 问题运行时错误:引用绑定到“struct value_type”类型的空指针(stl_vector.h)
- python - 如何将熊猫数据框写入csv文件?如何从最终字典中删除列表数组大括号([])?
- python - Python乘法相当于整数除法
- android - Msfvenom 有效负载卡在 termux 目录中
- c++ - OpenCV C++/Obj-C:检测一张纸/矩形检测
- c# - '对象不包含'InsertParameters'的定义
- iis - 使用 IIS 阻止对单个子文件夹的 Web 访问?