0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Spring Boot × React】②「Hello World」を表示するまで(バックとフロントの接続編)

Posted at

シリーズ構成
① 環境構築 ✅
Spring Boot「Hello world」生成/React「バックの値を表示」 ←本記事
③ Spring Boot は「React からの受け取り」/React は「日付入力」
④〜⑦ ToDo アプリ CRUD 機能


🎯 ゴール

React(http://localhost:3000) から
Spring Boot(http://localhost:8080) の API にアクセスして
「Hello world」 を画面に表示できるようにします。


🧩 前提:フォルダ構成(前回までの続き)

todo-tutorial/
├─ backend/   … Spring Boot(8080)
└─ frontend/  … React(3000)

1️⃣ Spring Boot 側:Hello API を作る

1-1. Controller を作成

backend/src/main/java/com/example/backend/controller/HelloController.java

package com.example.backend.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/api/hello")
    public String hello() {
        return "Hello world from Spring Boot!";
    }
}

1-2. 起動して確認

cd backend
.\gradlew bootRun

ブラウザで http://localhost:8080/api/hello にアクセス
"Hello world from Spring Boot!" と表示されれば成功!


2️⃣ React 側:バックの値を表示

2-1. 開発サーバ起動確認

別のターミナルを開いて:

cd frontend
npm start

http://localhost:3000 にアクセスし、React 初期画面が出ればOK。


2-2. App.js を編集

frontend/src/App.js を次のように書き換えます。

import React, { useEffect, useState } from "react";

function App() {
  const [message, setMessage] = useState("Loading...");

  useEffect(() => {
    // Spring BootのAPI呼び出し
    fetch("/api/hello")
      .then((res) => res.text())
      .then((data) => setMessage(data))
      .catch((err) => {
        console.error(err);
        setMessage("Error: APIに接続できませんでした。");
      });
  }, []);

  return (
    <div style={{ textAlign: "center", marginTop: "100px" }}>
      <h1>{message}</h1>
    </div>
  );
}

export default App;

💡 解説:

  • useEffect:コンポーネントが表示された直後に一度だけAPI呼び出しを行う。
  • fetch("/api/hello")
    package.json の "proxy": "http://localhost:8080" 設定により
    → 実際は http://localhost:8080/api/hello に転送される。

2-3. 動作確認

  1. backend(8080) が起動している状態で
  2. frontend(3000) を開く

→ 画面中央に
Hello world from Spring Boot!
と表示されればOK🎉


3️⃣ CORS/通信エラーが出たとき

  • 症状: コンソールに "CORS policy" のエラーが出る
  • 原因: proxy 設定が反映されていない/npm start を再起動していない

対処法

  1. frontend/package.json に以下が含まれているか確認:
"proxy": "http://localhost:8080"
  1. 保存後、npm start を再実行する。

それでもダメな場合は、Spring Boot 側に CORS 設定を一時的に追加します(学習用)。

@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/api/hello")
public String hello() {
    return "Hello world from Spring Boot!";
}

4️⃣ コードのポイント

ファイル 役割
HelloController.java API(バックエンド)
App.js 表示(フロントエンド)
package.json プロキシ設定でポート越え通信を解決
fetch("/api/hello") React→Spring Boot通信の基本形

5️⃣ トラブルシューティング

症状 原因・対応
"TypeError: Failed to fetch" backend が起動していない/URLミス
画面が真っ白 App.js の構文エラー(セミコロン抜けなど)
CORS エラー proxy 未設定 or React の再起動が必要
“Cannot find module ‘react’” npm install を再実行

6️⃣ 発展:JSON形式のAPIにしてみよう(応用)

今後のToDoアプリではJSON通信を使うため、試しに変更してみましょう。

@GetMapping("/api/hello")
public Map<String, String> hello() {
    return Map.of("message", "Hello world from Spring Boot (JSON)!");
}

React側:

fetch("/api/hello")
  .then((res) => res.json())
  .then((data) => setMessage(data.message));

→ これでJSON通信の基本が体験できます。


✅ まとめ

項目 内容
Spring Boot /api/hello を返すControllerを作成
React fetch("/api/hello") で値を取得して表示
通信方法 proxy設定でポート越え通信を解決
ゴール 「Hello world」が画面に表示される
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?