序章

Axios は、HTTPリクエストを作成できるオープンソースライブラリです。 .get().post()、および.delete()を含むメソッドを提供します。

この記事では、Axiosを使用してサーバーに対してGETPOST、およびDELETEリクエストを実行し、ToDoアイテムのリストを更新するJavaScriptアプリケーションを作成します。

前提条件

このチュートリアルを完了するには、次のものが必要です。

このチュートリアルは、ノードv15.11.0、npm v7.6.1、axios v0.21.1、およびparcel-bundlerv1.12.5で検証されました。

ステップ1—プロジェクトの設定

このセクションでは、新しいプロジェクトディレクトリを作成し、パッケージの依存関係をインストールして、構成ファイルを確立します。

まず、新しいプロジェクトディレクトリを作成します。

  1. mkdir axios-js-example

次に、新しいプロジェクトディレクトリに移動します。

  1. cd axios-js-example

次に、新しいnpmプロジェクトを初期化します。

  1. npm init -y

次に、Axiosをインストールします。

  1. npm install axios@0.21.1

注:AxiosはCDNを介して追加することもできます。

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Parcel は、コードをバンドルして提供するためのツールです。 parcel-bundlerを開発依存関係としてインストールします。

  1. npm install parcel-bundler@1.12.5 --save-dev

この時点で、axiosparcel-bundlerを使用した新しいプロジェクトが作成されます。

次に、コードエディタでpackage.jsonを開きます。 そして、"scripts"を変更して、devおよびbuildに対してparcelを実行します。

package.json
{
  // ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "parcel index.html",
    "build": "parcel build index.html"
  }
  // ...
}

次に、新しいapp.jsファイルを作成します。 また、awaitおよびasyncを使用するときに「regeneratorRuntime is not defined」エラーを回避するために、次のコード行を追加します。

app.js
import 'regenerator-runtime/runtime';
import axios from 'axios';

次に、新しいindex.htmlファイルを作成します。 そして、次のコード行を追加します。

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vanilla Axios</title>
  <style>
    body {
      background-color: #673AB7;
      color: white;
    }
    ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    li {
      margin-bottom: .5em;
      margin-top: .5em;
      padding: 1em;
      border: 1px solid white;
      transition-property: background-color, color;
      transition-duration: 500ms;
      transition-timing-function: ease-in-out;
    }
    li:hover {
      background-color: white;
      color: black;
    }
  </style>
</head>
<body>
  <div>
    <h1>Todos</h1>
    <ul>

    </ul>
  </div>
  <script src="app.js"></script>
</body>
</html>

このコードは、ToDoアイテムの順序付けられていないリストを作成します。 現在、このリストは空になりますが、後で入力されます。

ここで、プロジェクトがこの時点まで機能していることを確認します。 ターミナルを開き、次のコマンドを実行します。

  1. npm run dev

次に、ブラウザでhttp://localhost:1234/に移動します。 Todosという画面が表示されます。

ステップ2—GETリクエストを定義する

このセクションでは、Axiosを利用してGETHTTPリクエストをJSONプレースホルダーAPIに実行する関数を作成します。

コードエディタでapp;jsを開きます。 そして、次のコード行を追加します。

app.js
// ...

const BASE_URL = 'https://jsonplaceholder.typicode.com';

const getTodoItems = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/todos?_limit=5`);

    const todoItems = response.data;

    console.log(`GET: Here's the list of todos`, todoItems);

    return todoItems;
  } catch (errors) {
    console.error(errors);
  }
};

axios.getBASE_URL"todos"文字列から構築されたパスをどのように渡されるかに注目してください。 _limitパラメーターは、応答を5アイテムに制限します。

このメソッドは、responseオブジェクトを返します。 これには、headersstatusconfig、そして最も重要なdataなどの応答に関する情報が含まれます。

次に、Todo要素を作成するコードを追加し、Todo要素をリストに追加します。

app.js
// ...

const createTodoElement = item => {
  const todoElement = document.createElement('li');

  todoElement.appendChild(document.createTextNode(item.title));

  return todoElement;
};

const updateTodoList = todoItems => {
  const todoList = document.querySelector('ul');

  if (Array.isArray(todoItems) && todoItems.length > 0) {
    todoItems.map(todoItem => {
      todoList.appendChild(createTodoElement(todoItem));
    });
  } else if (todoItems) {
    todoList.appendChild(createTodoElement(todoItems));
  }
};

const main = async () => {
  updateTodoList(await getTodoItems());
};

main();

変更を保存し、ブラウザでアプリケーションを表示します。 5つのアイテムのリストを確認します。

ステップ3—POSTリクエストを定義する

このセクションでは、formおよびinputを作成して、リストに追加する新しいToDoアイテムの情報を取得します。 Axiosを利用してPOSTHTTPリクエストを実行します。

コードエディタでindex.htmlを開きます。 そして、次のコード行を追加します。

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- ... -->
  <style>
    /* ... */
    #new-todos form {
      margin-bottom: .5em;
      margin-top: .5em;
      padding: 1em;
      border: 1px solid white;
    }
  </style>
</head>
<body>
  <div id="new-todos">
    <h1>New Todo</h1>
    <form>
      <label>
        Name
        <input type="text" id="new-todos__title" />
      </label>
      <button type="submit">Add</button>
    </form>
  </div>
  <div>
    <h1>Todos</h1>
    <ul>

    </ul>
  </div>
  <script src="app.js"></script>
</body>
</html>

次に、コードエディタでapp.jsを開きます。 そして、次のコード行を追加します。

app.js
// ...

const form = document.querySelector('form');

form.addEventListener('submit', async event => {
  event.preventDefault();

  const title = document.querySelector('#new-todos__title').value;

  const todo = {
    userId: 1,
    title: title,
    completed: false
  };

  const submitTodoItem = await addTodoItem(todo);
  updateTodoList(submitTodoItem);
});

このコードはフォームから値を取得し、todoオブジェクトを作成します。

次に、app.js内でaddTodoItem関数を定義する必要があります。

app.js
// ...

export const addTodoItem = async todo => {
  try {
    const response = await axios.post(`${BASE_URL}/todos`, todo);
    const newTodoItem = response.data;

    console.log(`Added a new Todo!`, newTodoItem);

    return newTodoItem;
  } catch (errors) {
    console.error(errors);
  }
};

axios.postにtodoアイテムを含むパスとペイロードがどのように渡されるかに注目してください。

変更を保存し、ブラウザでアプリケーションを表示します。 5つのアイテムとフォームを含むリストを確認します。 フォームを使用して新しいToDoアイテムを追加すると、リストが更新されて6つのアイテムが表示されます。

ステップ4—DELETEリクエストを定義する

このセクションでは、既存のToDoアイテムに対してクリックイベントを作成して、リストから削除します。 Axiosを利用してDELETEHTTPリクエストを実行します。

次に、app.js内でdeleteTodoItem関数を定義する必要があります。

app.js
// ...

export const deleteTodoItem = async id => {
  try {
    const response = await axios.delete(`${BASE_URL}/todos/${id}`);
    console.log(`Deleted Todo ID: `, id);

    return response.data;
  } catch (errors) {
    console.error(errors);
  }
};

axios.deleteに、todoアイテムのidを含むパスが渡されることに注意してください。

次に、removeTodoElement関数を作成します。

app.js
// ...

const removeTodoElement = async (event, element) => {
  event.target.parentElement.removeChild(element);
  const id = element.id;

  await deleteTodoItem(id);
};

このコードは、DOMから要素を削除してから、idを使用してdeleteTodoItemを呼び出します。

ここで、createTodoElement機能までスクロールして戻ります。 2行の新しいコードを追加します。 リストアイテム要素が作成されたら、要素にonclickイベントを追加して削除します。 アイテムidを受け取り、それをremoveTodoElementに渡し、deleteTodoItemを呼び出します。

app.js
// ...

const createTodoElement = item => {
  const todoElement = document.createElement('li');

  todoElement.id = item.id;
  todoElement.appendChild(document.createTextNode(item.title));

  todoElement.onclick = async event => await removeTodoElement(event, todoElement);

  return todoElement;
};

// ...

変更を保存し、ブラウザでアプリケーションを表示します。 5つのアイテムとフォームを含むリストを確認します。 フォームを使用して新しいToDoアイテムを追加すると、リストが更新されて6つのアイテムが表示されます。 ToDoアイテムの1つをクリックすると、リストに5つのアイテムが表示されます。

結論

この記事では、Axiosを使用してサーバーに対してGETPOST、およびDELETEリクエストを実行し、ToDoアイテムのリストを更新するJavaScriptアプリケーションを作成しました。

Axiosの詳細については、 React withAxiosおよびVuewithAxiosのガイドをご覧ください。