Menu
CoddyTech

クエリ文字列

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

リストページでは、表示するレシピなどのオプションが必要になることがよくありますが、オプションごとに新しいルートを作るのは多すぎます。

app.get('/books', (req, res) => {
    const { author } = req.query;
    res.send(author ? 'Books by ' + author : 'All books');
});

クエリ文字列はURLの?以降の部分で、Expressはそれをreq.queryに格納します。GET /books?author=Austenの場合、req.query.author === 'Austen'になります。?がない場合はundefinedです。複数のオプションは&でつなぎます。/books?author=Austen&year=1813のようになります。

ルートパラメーターはパスの一部で、1つのものを指定します。クエリオプションはリストを絞り込んだり並べ替えたりするためのもので、省略できます。

challenge icon

チャレンジ

簡単
  • GET /recipes?tag=vegan は、そのタグが付いたレシピのタイトルだけを1行に1つずつ一覧表示します。
  • tag を指定しない場合は、すべてのタイトルを一覧表示します。

GET /recipes?tag=vegan、GET /recipes?tag=dessert、GET /recipes を送信します。

自分で試してみよう

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('/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('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

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

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