Menu
CoddyTech

404 처리기

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

Express는 알 수 없는 경로에 대해 자체 페이지인 Cannot GET /x로 응답하는데, 이는 사이트에도 API에도 어울리지 않습니다.

app.use((req, res) => {
    res.status(404).send('No forecast here. Try /weather/oslo');
});

경로가 지정되지 않은 미들웨어는 해당 미들웨어에 도달하는 모든 요청에 실행됩니다. 이 미들웨어를 모든 라우트와 express.static 뒤에 배치하세요. 라우트나 정적 파일 미들웨어가 응답한 요청은 여기에 도달하지 않으므로, 아무것도 응답하지 않은 요청만 처리합니다. 이 미들웨어가 응답하므로 next는 필요하지 않습니다.

req.path는 쿼리 문자열을 제외한 경로이므로, req.path.startsWith('/api/')를 사용하면 API 호출과 페이지 요청을 구분할 수 있습니다.

challenge icon

챌린지

쉬움
  • 아무것도 응답하지 않는 /api/ 경로는 404와 { "error": "Not found" }를 반환합니다.
  • 그 밖의 경로는 Page not found라고 표시된 404 HTML 페이지를 반환합니다.

GET /api/nope를 보내고, 페이지 보기에서 /nope를 연 다음, GET /api/recipes/1을 보내세요.

직접 해보기

import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';

const app = express();

app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

app.use((req, res, next) => {
    res.set('X-Request-Id', randomUUID());
    next();
});

app.use(express.json());

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

const escapeHtml = (text) =>
    text
        .replaceAll('&', '&')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');

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.post('/api/recipes', (req, res) => {
    const { title, tags } = req.body;
    if (!title) {
        res.status(400).json({ error: 'A recipe needs a title' });
        return;
    }
    const recipe = { id: recipes.length + 1, title, tags: tags ?? [] };
    recipes.push(recipe);
    res.status(201).json(recipe);
});

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

app.get('/menu', (req, res) => {
    res.redirect(301, '/recipes');
});

app.get('/menu/:id', (req, res) => {
    res.redirect(301, `/recipes/${req.params.id}`);
});

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

Express 기초의 모든 레슨