LoginSignup
4
0

More than 1 year has passed since last update.

JSON ServerでモックアップAPIを作成

Last updated at Posted at 2023-04-02

◆ Json Serverとは

Node.jsのライブラリの1つ。
特定のリクエストを送信すると、Jsonを返してくれるサーバーを簡易的に作成することができる。

複雑な処理を行うことはできないため、本番用ではなく開発用として使用するのが良い。



◆ Json Serverのインストール

・コマンド

npm install -D json-server


◆ Jsonファイルを用意する。

Json Serverが呼び出す用のJsonファイルを用意する。これがモックデータとなる。

【補足】

モック(モックアップ):とは、Mockという英単語で、「見せかけ」、「まがいもの」という意味。



App
 └ db
    └ db.json

・db.json

{
  "todo": [
    {
      "id": "c5868bfe-fa1d-4891-acd3-bc43959a9bb7",
      "content": "洗濯",
      "editing": false,
      "completed": true
    },
    {
      "id": "5d87d115-7ebb-4d17-adce-4ffe4b39f8c5",
      "content": "掃除",
      "editing": false,
      "completed": false
    },
    {
      "id": "f2c38014-e2df-40ae-ac93-36303b8771ce",
      "content": "買い物",
      "editing": false,
      "completed": false
    }
  ],
  "user": [
    {
      "id": 1,
      "username": "hoge太郎",
      "age": 20,
      "hobbies": [
        "サッカー",
        "野球"
      ],
      "premiumAccount": true
    },
    {
      "id": 2,
      "username": "fuga太郎",
      "age": 17,
      "hobbies": [
        "カメラ"
      ],
      "premiumAccount": false
    },
    {
      "id": 3,
      "username": "piyo三郎",
      "age": 50,
      "hobbies": [
        "筋トレ",
        "水泳"
      ],
      "premiumAccount": true
    }
  ]
}


◆ Json Serverの起動

Jsonファイルの用意が完了したら、コマンドでJson Serverを呼び出す。

・Json Serverの起動コマンド

// コマンド
json-server -watch jsonファイル -p ポート番号


// 今回の場合
npx json-server -watch ./db/db.json


// ポートを指定したい場合
npx json-server -watch ./db/db.json -p 3003


◆ リクエストを実行

ブラウザからリクエストを実行し、該当のJsonデータがレスポンスでレスポンスで返ってくる事を確認。

・リクエスト
スクリーンショット 2023-04-02 11.06.18.png

・レスポンス
スクリーンショット 2023-04-02 11.07.36.png
レスポンスが画面に表示される。



◆ axiosを使ってサーバーからデータを取得

・async awaitを使わない場合

import { useEffect } from "react";
import axios from "axios";

const Example = () => {
  useEffect(() => {
    const getResponse = async () => {
      axios.get("http://localhost:3003/todo")
                .then((res) => { console.log(res.data) });
    };
    getResponse();
  });
  return <></>;
};

export default Example;

・async awaitを使う場合

import { useEffect } from "react";
import axios from "axios";

const Example = () => {
  useEffect(() => {
    const getResponse = async () => {
      const res = await axios.get("http://localhost:3003/todo");
      console.log(res.data);
    };
    getResponse();
  });
  return <></>;
};

export default Example;



◆ 注意点

useEffectのコールバック関数の先頭には「asyncを記入してはいけない」というルールがある。

  // NG ×
  useEffect( async () => {
      const res = await axios.get("http://localhost:3003/todo");
      console.log(res.data);
    };
  });

なのでuseEffectでasync・awaitを利用するときは、useEffect内で新しく別の関数を定義し、その関数にasync・awaitを記入する。



◆ UIにレスポンスを表示してみる

UIに表示する際は、レスポンスを ステートで管理して表示する。

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

const Example = () => {
  // レスポンスを管理するステート
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const getUser = async () => {
      const res = await axios.get("http://localhost:3003/user");
      setUsers(res.data);
    };
    getUser();
  }, []);

  return (
    <div>
      {users.map((user) => {
        return (
          <div key={user.id}>
            <h3>Name: {user.username}</h3>
            <p>Age: {user.age}</p>
            <p>Hobby: {user.hobbies.join(",")}</p>
          </div>
        );
      })}
    </div>
  );
};

export default Example;

画面

スクリーンショット 2023-04-02 14.15.43.png

4
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
4
0