← レベル3 – マスター

レッスン 9/10 ⏱ 60 分 プレミアム

ゲストブック:フロントとバックを一緒に

大きな瞬間:React をサーバーに接続。メッセージが本当に保存される。

作るもの

ゲストブック: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");
});

新しいもの:

見てみよう:ゲストブックのフロントエンド

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つの新しいこと:

やってみよう 💪

  1. 両方動かす:1つのターミナルでサーバー(node server.js)、もう1つで React(npm run dev -- --port 3901)。2ターミナル、2プログラム——フルスタックへようこそ!
  2. アプリに <GuestBook /> を追加して試す:メッセージを書く、ページを再読み込み——メッセージがまだある(サーバーが動いてる限り)。
  3. プロジェクトに合わせてゲストブックを調整:🏫 学校へのメッセージ · 🙋 友達用掲示板 · 🌍 訪問者からの「次はどこ?」 · ⚽ ファンのチャント。
  4. 空メッセージを送ってみる——フロントエンドは通す(チェックなし)が、サーバーは拒否。レベル2みたいにフロントエンドにもチェックを追加。
💡

サーバー再起動でメッセージは消える——メモリ内の配列にしかない。本番アプリは データベース に保存して何があっても残す。レベル修了後の最初の学び——キーワード:SQLite、PostgreSQL。

✅

確認: フォームからのメッセージがサーバーへ行き、保存され、ページ再読み込み後も戻る。フルスタックアプリケーション を作った——フロントエンド、バックエンド、API。プロの開発者が毎日やってることそのもの。

このレッスンのまとめ