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?

JSON ServerでモックアップAPIを作成し、Axiosでデータを取得する

Posted at

本記事では、JSON Serverを使用して簡単なモックAPIを作成し、Axiosを使ってサーバーからデータを取得する方法を解説します。

用語説明

JSON Server: JSON形式のデータをAPIとして提供できる簡単なツール。開発時のモックAPIとして利用される。

Axios: HTTPリクエストを簡単に送受信できるJavaScriptライブラリ。

モックAPI: 実際のAPIの動作を模倣したテスト用のAPI。開発中にバックエンドが未完成の状態でもフロントエンドの開発やテストを進められる。

環境準備

Node.jsのインストール

Node.jsがインストールされていない場合、公式サイトからインストールしてください。

JSON Serverのインストール

npm install -g json-server

Axiosのインストール

Reactプロジェクトで使用する場合

npm install axios

Node.jsで使用する場合も同様にインストール可能です。

JSON Serverの設定

JSONファイルの作成
db.jsonというファイルを作成し、以下のように記述します。

{
  "users": [
    { "id": 1, "name": "Taro", "email": "taro@example.com" },
    { "id": 2, "name": "Hanako", "email": "hanako@example.com" }
  ]
}

JSON Serverの起動

json-server --watch db.json --port 3001

--watch db.json:変更を監視

--port 3001:デフォルトの3000以外のポートで起動

Axiosでデータを取得

ReactでJSON Serverからデータを取得する例を示します。

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:3001/users')
      .then(response => {
        setUsers(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>ユーザー一覧</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name} ({user.email})</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

まとめ

JSON Serverを使うことで簡単にモックAPIを作成できる。

json-server --watch db.json --port 3001 でサーバーを起動。

Axiosを使い、ReactのuseEffectでデータを取得。

以上の手順で、モックAPIの作成とデータ取得の基本が理解できます。ぜひ試してみてください!

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?