ルートパラメータ
CoddyのNode.jsジャーニー「Expressの基礎」セクションの一部。レッスン 4/20。
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')はステータスを設定してから、レスポンスを送信します。
チャレンジ
簡単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');
});
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。