Menu
CoddyTech

検索ページ

CoddyのNode.jsジャーニー「Expressの基礎」セクションの一部。レッスン 23/23。

検索ページはフォームであり、サーバーは他のGETリクエストと同様に応答します。

<form action="/books" method="get">
    <input name="author">
    <button>Find</button>
</form>

このフォームを送信すると、ブラウザーは/books?author=の後に、authorという名前のフィールドに入力された内容を付けたURLに移動します。ルートはreq.queryからその値を読み取ります。その単語をフィールドのvalueとして書き戻すと、検索後も表示されたままになります。これは訪問者から送られた値なので、エスケープしてください。

challenge icon

チャレンジ

簡単

Recipe Box に検索ページを追加します。訪問者が単語を入力すると、その単語をタイトルに含むレシピがページに一覧表示されます。

  1. server.js で、404 ハンドラーの上に、/search 用の非同期ルートを追加します。req.query.q から単語を読み取り、指定されていない場合は空文字列を使います。
  2. ページには常に検索フォームがあります。テキストフィールドの名前を q にし、ボタンを付けた <form action="/search" method="get"> を使います。送信すると、単語に続けて /search?q= を開きます。
  3. 検索した単語がフィールドに表示されます。たとえば curry を検索した後は、フィールドに curry が入っています。訪問者が入力した値なので、escapeHtml を通してから、フィールドの value 属性に書き込みます。
  4. フォームの下に、loadRecipes() のすべてのレシピのうち、タイトルにその単語を含むものへのリンクを、大文字と小文字を区別せずに一覧表示します。soup と SOUP のどちらでも Tomato Soup が見つかります。各リンクはレシピのページに移動し、ホームページと同じようにエスケープしたタイトルを表示します。例: <a href="/recipes/1">Tomato Soup</a>。
  5. 単語を検索しても、それを含むタイトルがない場合は、リストの代わりに No recipes found というテキストを表示します。

試してみましょう: 「実行」を押して /search にアクセスします。空のフォームが表示されます。フィールドに SOUP と入力して、ボタンを押します。ページには Tomato Soup が一覧表示され、フィールドには引き続き SOUP と表示されます。pizza を検索すると、No recipes found と表示されます。fish を検索すると、Fish & Chips が正しく表示されます。次に、{"title": "Pea Soup", "tags": ["soup"]} を /api/recipes に POST して、もう一度 soup を検索します。Pea Soup も一覧に表示されます。

自分で試してみよう

import { escapeHtml } from './html.js';
import { dayOfYear } from './day-of-year.js';
import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
import recipesRouter, { loadRecipes } from './routes/recipes.js';
import reviewsRouter from './routes/reviews.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'));

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.use('/api/recipes', recipesRouter);
app.use('/api/recipes/:id/reviews', reviewsRouter);

app.get('/api/today', async (req, res) => {
    const day = dayOfYear(req.query.date);
    if (day === null) {
        res.status(400).json({ error: 'Use a date like 2026-03-01' });
        return;
    }
    const recipes = await loadRecipes();
    res.json(recipes[day % recipes.length]);
});

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.use((req, res) => {
    if (req.path.startsWith('/api/')) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    res.status(404).send('<h1>Page not found</h1><p><a href="/">Back to Recipe Box</a></p>');
});

app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).json({ error: 'Something went wrong' });
});

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

Expressの基礎のすべてのレッスン

自分で練習してみよう: Expressプレイグラウンド