JavaScriptでAxiosを使用する方法
序章
Axios は、HTTPリクエストを作成できるオープンソースライブラリです。 .get()
、.post()
、および.delete()
を含むメソッドを提供します。
この記事では、Axiosを使用してサーバーに対してGET
、POST
、およびDELETE
リクエストを実行し、ToDoアイテムのリストを更新するJavaScriptアプリケーションを作成します。
前提条件
このチュートリアルを完了するには、次のものが必要です。
- Node.jsのローカル開発環境。 Node.jsをインストールしてローカル開発環境を作成する方法に従ってください。
このチュートリアルは、ノードv15.11.0、npm
v7.6.1、axios
v0.21.1、およびparcel-bundler
v1.12.5で検証されました。
ステップ1—プロジェクトの設定
このセクションでは、新しいプロジェクトディレクトリを作成し、パッケージの依存関係をインストールして、構成ファイルを確立します。
まず、新しいプロジェクトディレクトリを作成します。
mkdir axios-js-example
次に、新しいプロジェクトディレクトリに移動します。
cd axios-js-example
次に、新しいnpm
プロジェクトを初期化します。
npm init -y
次に、Axiosをインストールします。
npm install [email protected]
注:AxiosはCDNを介して追加することもできます。
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Parcel は、コードをバンドルして提供するためのツールです。 parcel-bundler
を開発依存関係としてインストールします。
npm install [email protected] --save-dev
この時点で、axios
とparcel-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アイテムの順序付けられていないリストを作成します。 現在、このリストは空になりますが、後で入力されます。
ここで、プロジェクトがこの時点まで機能していることを確認します。 ターミナルを開き、次のコマンドを実行します。
npm run dev
次に、ブラウザでhttp://localhost:1234/
に移動します。 Todos
という画面が表示されます。
ステップ2—GET
リクエストを定義する
このセクションでは、Axiosを利用してGET
HTTPリクエストを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.get
がBASE_URL
と"todos"
文字列から構築されたパスをどのように渡されるかに注目してください。 _limit
パラメーターは、応答を5
アイテムに制限します。
このメソッドは、response
オブジェクトを返します。 これには、headers
、status
、config
、そして最も重要な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を利用してPOST
HTTPリクエストを実行します。
コードエディタで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を利用してDELETE
HTTPリクエストを実行します。
次に、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を使用してサーバーに対してGET
、POST
、およびDELETE
リクエストを実行し、ToDoアイテムのリストを更新するJavaScriptアプリケーションを作成しました。
Axiosの詳細については、 React withAxiosおよびVuewithAxiosのガイドをご覧ください。