🧐

ReactアプリからExpress APIを呼んでデータを表示してみた

に公開

🌟目標

Reactのプロジェクトを1から作成して、axiosでAPIを呼ぶ準備までやる
以前の記事の続きにもなっています
https://zenn.dev/rikahanai/articles/deb1e481d8d13e

1. Reactプロジェクトを作る

ターミナルに移動して、以下をコピペして実行
Vite(速くて簡単) を使ったReact + TypeScriptプロジェクト作成

npm create vite@latest my-react-api-app -- --template react-ts
  • my-react-api-app は任意のプロジェクト名
  • -template react-ts → React + TypeScriptのテンプレート

2. プロジェクトに移動して依存パッケージをインストール

cd my-react-api-app
npm install

3. axiosをインストール

APIを呼ぶためのaxiosもインストール

npm install axios

4. プロジェクトを起動

npm run dev

👇出力に出ているURLをブラウザで開く

Local:   http://localhost:5173/

Reactアプリの最初の画面が表示される

5. App.tsxを編集してAPIを呼ぶ

  1. プロジェクトのフォルダをVSCodeで開く
  2. src/App.tsx の中身を以下の通りに変更
App.tsx
import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const [message, setMessage] = useState<string>('');

  useEffect(() => {
    axios.get('http://localhost:3001/api/message')
      .then((response) => {
        console.log(response.data);  // 確認用ログ
        setMessage(response.data.message);
      })
      .catch((error) => {
        console.error('APIエラー:', error);
      });
  }, []);

  return (
    <div style={{ padding: '20px' }}>
      <h1>APIからのメッセージ:</h1>
      <p>{message ? message : '読み込み中...'}</p>
    </div>
  );
}

export default App;
エラー例:Access to XMLHttpRequest at 'http://localhost:3001/api/message' from origin '[http://localhost:5173](http://localhost:5173/)' has been blocked by CORS policy: ...

  1. Expressサーバー側でcorsをインストール:
npm install cors

以前作成したExpressサーバーはこちら
https://zenn.dev/rikahanai/articles/deb1e481d8d13e

  1. index.jsを修正
index.js
const express = require("express");
const cors = require("cors"); // 追記
const app = express();

app.use(cors()); // 追記
app.use(express.json());

app.get("/api/message", (req, res) => {
  res.json({ message: "Hello from the API!" });
});

app.listen(3001, () => {
  console.log("API running on http://localhost:3001");
});

Expressサーバーを再起動(Ctrl+C → node index.js)して確認

「Hello from the API!」が表示されたらOK🎉

Discussion