首页 > 解决方案 > 无法使 @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”?当然,我不应该手动解析字符串。

标签: nestjs

解决方案


您将 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


推荐阅读