Menu
CoddyTech

라우트 매개변수

Coddy Node.js 여정의 Express 기초 섹션에 포함된 레슨. 20개 중 4번째.

Recipe Box에는 많은 레시피가 들어가므로, 레시피마다 경로를 하나씩 만들면 끝이 없을 것입니다.

app.get('/weather/:city', (req, res) => {
    res.send('Forecast for ' + req.params.city);
});

콜론으로 시작하는 경로 부분은 경로 매개변수입니다. 이 부분은 어떤 값이든 일치하며, Express는 그 값을 req.params에 넣습니다. GET /weather/oslo는 Forecast for oslo를 보냅니다.

매개변수는 항상 문자열입니다. GET /rooms/12는 '12'를 반환하며, '12' === 12는 false이므로 숫자와 비교하기 전에 Number(...)를 사용해 변환하세요.

요청한 항목이 없으면 상태 코드 404로 응답하세요. res.status(404).send('No such city')는 상태를 설정한 다음 응답을 보냅니다.

challenge icon

챌린지

쉬움
  • GET /recipes/:id는 해당 id를 가진 레시피의 제목을 반환합니다.
  • 알 수 없는 id에는 404와 No such recipe를 반환합니다.

GET /recipes/2를 보낸 다음 GET /recipes/99를 보내세요.

직접 해보기

import express from 'express';
import { recipes } from './data.js';

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Recipe Box');
});

// type('text')는 일반 텍스트를 전송하므로 각 제목이 한 줄씩 표시됩니다.
app.get('/recipes', (req, res) => {
    res.type('text').send(recipes.map((recipe) => recipe.title).join('\n'));
});

app.get('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Express 기초의 모든 레슨