Menu
CoddyTech

라우트 매개변수

Coddy Node.js 여정의 TypeScript와 NestJS 섹션에 포함된 레슨. 17개 중 2번째.

클라이언트는 전체 목록이 아니라 작업 하나만 필요한 경우가 많습니다. 경로에는 매 요청마다 달라지는 부분인 매개변수가 포함될 수 있습니다.

@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

챌린지

쉬움
  • GET /tasks/:id를 추가하세요. 이 경로는 해당 id의 작업을 반환합니다.
  • GET /tasks/2를 보낸 다음 GET /tasks/99를 보내고, 작업이 없는 id에 어떤 응답이 오는지 확인하세요.

직접 해보기

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의 모든 레슨