作るもの
ゲストブック:React のフォームがサーバーにメッセージを送り、サーバーが保存して、将来の訪問者全員に表示。レベル2で行き先のなかったフォーム? 今日その借金を返す。
見てみよう:ゲストブックのバックエンド
my-server フォルダで、もう1パッケージをインストール:
npm install cors
server.js を編集:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors()); // allow the frontend on a different port to ask questions
app.use(express.json()); // understand JSON in incoming requests
const messages = [
{ name: "Martin", text: "First message! Long live the guestbook. 📖" },
];
// GET – hand out messages
app.get("/api/messages", (request, response) => {
response.json(messages);
});
// POST – accept a new message
app.post("/api/messages", (request, response) => {
const { name, text } = request.body;
// Never trust input: check it on the server too!
if (!name || !text || name.length > 50 || text.length > 500) {
return response.status(400).json({ error: "Invalid message." });
}
messages.push({ name, text });
response.json({ saved: true });
});
app.listen(3900, () => {
console.log("Server running at http://localhost:3900");
});
新しいもの:
cors()– フロントエンドは3901、サーバーは3900。ブラウザは通常こういう「クロスオリジン」リクエストをブロック(CORS というセキュリティルール);サーバー側で許可する。app.post(...)– 最初の POST エンドポイント! フォームデータはrequest.bodyに現れる。- サーバー側チェック – フロントエンドはすでにフォームをチェックするが、攻撃者はフォームを bypass して直接リクエストできる。だから鉄則:バックエンドは常にチェックし、フロントエンドを信用しない。
status(400)= 「不正なリクエスト」。
見てみよう:ゲストブックのフロントエンド
React プロジェクトで src/GuestBook.jsx を作成:
import { useState, useEffect } from 'react';
function GuestBook() {
const [messages, setMessages] = useState([]);
const [name, setName] = useState("");
const [text, setText] = useState("");
// On first render: download the messages from the server
useEffect(() => {
fetch("http://localhost:3900/api/messages")
.then((response) => response.json())
.then((data) => setMessages(data));
}, []);
function submit(event) {
event.preventDefault();
fetch("http://localhost:3900/api/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, text }),
})
.then((response) => response.json())
.then(() => {
setMessages([...messages, { name, text }]); // add it to the screen too
setName("");
setText("");
});
}
return (
<div>
<h2>Guestbook 📖</h2>
{messages.map((message, index) => (
<div className="card" key={index}>
<strong>{message.name}</strong>
<p>{message.text}</p>
</div>
))}
<form onSubmit={submit}>
<input
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Your name"
/>
<textarea
value={text}
onChange={(event) => setText(event.target.value)}
placeholder="Write a message..."
/>
<button type="submit">Send</button>
</form>
</div>
);
}
export default GuestBook;
React の最後の3つの新しいこと:
useEffect(() => {...}, [])– 「コンポーネントが初めて表示されたときに1回実行。」データダウンロードに最適。method: "POST"付きfetch– データを送る;JSON.stringifyで JSON にパック。- 接続フォーム – フィールドは state から値を読む(
value={name})、入力中に書き戻す(onChange)。フォームと state は常に同期。
やってみよう 💪
- 両方動かす:1つのターミナルでサーバー(
node server.js)、もう1つで React(npm run dev -- --port 3901)。2ターミナル、2プログラム——フルスタックへようこそ! - アプリに
<GuestBook />を追加して試す:メッセージを書く、ページを再読み込み——メッセージがまだある(サーバーが動いてる限り)。 - プロジェクトに合わせてゲストブックを調整:🏫 学校へのメッセージ · 🙋 友達用掲示板 · 🌍 訪問者からの「次はどこ?」 · ⚽ ファンのチャント。
- 空メッセージを送ってみる——フロントエンドは通す(チェックなし)が、サーバーは拒否。レベル2みたいにフロントエンドにもチェックを追加。
💡
サーバー再起動でメッセージは消える——メモリ内の配列にしかない。本番アプリは データベース に保存して何があっても残す。レベル修了後の最初の学び——キーワード:SQLite、PostgreSQL。
✅
確認: フォームからのメッセージがサーバーへ行き、保存され、ページ再読み込み後も戻る。フルスタックアプリケーション を作った——フロントエンド、バックエンド、API。プロの開発者が毎日やってることそのもの。
このレッスンのまとめ
useEffect(..., [])で初回レンダー時にデータ取得;POST 付きfetchで送信。- セキュリティの鉄則:フロントエンドもチェックしてても、サーバーはすべての入力をチェック。
- フルスタック = 2つの動くプログラム(3901 + 3900)が API で話す。
© 2026 Ing. Martin Polak / AlgoRhino · コンテンツ利用規約