Menu
CoddyTech

路由参数

本课属于 Coddy Node.js 学习旅程的“TypeScript 和 NestJS”单元。第 4 课,共 24 课。

客户端通常只需要一个任务,而不是整个列表。路径可以包含参数:路径中会随每次请求而变化的部分。

@Get(':isbn')
findOne(@Param('isbn') isbn: string) {
    return this.books.find((book) => book.isbn === isbn);
}

:isbn 会匹配路径中该位置的任意值,因此 GET /books/978 会调用这个方法。@Param('isbn') 会将该值传给方法。它始终是文本:/books/42 得到的是字符串 '42',而不是数字 42。

省略名称时,@Param() 会返回包含所有参数的对象 { isbn: '978' },而不是单个值。

challenge icon

挑战

简单

客户端通常只需要一个任务,而不是整个列表。添加一个路由,根据任务的 id 返回单个任务。

  1. 在 src/tasks/tasks.controller.ts 中,向 TasksController 添加第二个方法(命名为 findOne),用于处理 GET /tasks/:id。:id 表示路径中该位置可以是任意值,因此 /tasks/2 会匹配这个路由。
  2. 使用 @Param('id') 从路径中读取 id。从 @nestjs/common 导入 Param。
  3. id 会以文本形式传入,例如 "2",但 this.tasks 中的 id 是数字,而 "2" === 2 的结果是 false。比较之前,先把 id 转换为数字。
  4. 返回 id 与该值相同的任务。
  5. 保持 GET /tasks 不变:它仍然返回整个列表。

试试看:发送 GET /tasks/2。你会得到状态码 200 和以下结果:

{ "id": 2, "title": "Fix the login bug", "done": false }

也发送 GET /tasks/1 和 GET /tasks/3。然后发送 GET /tasks/99。没有任务的 id 是这个值,因此你的方法不会返回任何内容,而 Nest 会响应状态码 200 和一个空响应体。目前这是预期行为。这样的响应没有向客户端说明原因,后续的一课会修复这个问题。

亲手试试

import { Controller, Get } from '@nestjs/common';

interface Task {
    id: number;
    title: string;
    done: boolean;
}

@Controller('tasks')
export class TasksController {
    private tasks: Task[] = [
        { id: 1, title: 'Write the README', done: true },
        { id: 2, title: 'Fix the login bug', done: false },
        { id: 3, title: 'Plan the sprint', done: false },
    ];

    @Get()
    findAll(): Task[] {
        return this.tasks;
    }
}

TypeScript 和 NestJS中的所有课

自己练习: Express 在线编辑器