Menu
CoddyTech

리디렉션

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

페이지는 이동할 수 있으며, 북마크와 검색 결과에 있는 오래된 링크도 여전히 어딘가로 연결되어야 합니다.

app.get('/old-prices', (req, res) => {
    res.redirect(301, '/prices');
});

리디렉션은 상태 코드와 새 URL을 지정하는 Location 헤더를 응답으로 보내며, 브라우저는 즉시 해당 URL을 요청합니다. res.redirect는 둘 다 설정합니다.

상태 코드는 이동이 얼마나 오래 지속되는지 나타냅니다. 301은 영구적으로 이동했음을 의미합니다. 브라우저와 검색 엔진은 새 주소를 기억하고 이전 주소는 더 이상 요청하지 않습니다. 상태 코드를 전달하지 않을 때 기본값인 302는 일시적인 이동을 의미하므로, 브라우저와 검색 엔진은 이전 URL을 계속 사용합니다.

challenge icon

챌린지

쉬움

이전 메뉴 페이지는 이제 레시피 페이지로 영구적으로 이동했으며, 이전 북마크도 계속 작동해야 합니다.

  1. server.js에 /menu 경로를 추가하여 상태 코드 301로 /recipes로 리디렉션하세요. 상태 코드 301은 영구적으로 이동했음을 의미합니다.
  2. /menu/:id 경로를 추가하여 동일한 id를 가진 레시피 페이지로 상태 코드 301로 리디렉션하세요. /menu/3은 /recipes/3으로 이동합니다.

직접 해보기: ‘플레이’를 누르고 /menu/3을 전송하세요. 상태 코드 301과 /recipes/3 값이 있는 Location 헤더가 표시되어야 합니다. /menu를 전송하면 Location이 /recipes인 301 응답이 표시됩니다. /menu/42를 전송하면 Location이 /recipes/42인 301 응답이 표시됩니다. 리디렉션은 레시피 42가 존재하는지 확인하지 않습니다. 그런 다음 /recipes/42 자체가 404로 응답합니다.

직접 해보기

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

const app = express();

app.use(express.static('public'));

app.get('/', (req, res) => {
    const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
    res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});

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

app.get('/recipes/:id', (req, res) => {
    const recipe = recipes.find((r) => r.id === Number(req.params.id));
    if (!recipe) {
        res.status(404).send('No such recipe');
        return;
    }
    res.send(recipe.title);
});

app.get('/api/recipes', (req, res) => {
    res.json(recipes);
});

app.get('/api/recipes/:id', (req, res) => {
    const recipe = recipes.find((r) => r.id === Number(req.params.id));
    if (!recipe) {
        res.status(404).json({ error: 'No such recipe' });
        return;
    }
    res.json(recipe);
});

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

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

Express 기초의 모든 레슨

직접 연습해 보세요: Express 플레이그라운드