By PaulHalliday and christinagorton

Web 上の多くのプロジェクトは、開発の段階の一部で REST API とインターフェイスする必要があります。Axiosは、Angular.jsバージョン1系の$httpサービスに基づく軽量HTTPクライアントであり、ネイティブJavaScriptの Fetch API に似ています。
Axios は promiseベースであり、非同期コードをより読みやすくするために、JavaScript のasyncおよびawaitを活用することができます。
リクエストを傍受してキャンセルすることもでき、クロスサイトリクエストフォージェリに対するクライアント側の保護機能が組み込まれています。
この記事では、Axiosを使用して、Reactアプリケーション内の一般的な JSONプレースホルダーAPI にアクセスする方法の例を説明します。
この記事を進めるには、次のものが必要です。
このセクションでは、Create React Appを使用してReactプロジェクトをセットアップする方法のチュートリアルに従って作成したdigital-ocean-tutorial React プロジェクトにAxiosを追加します。
プロジェクトにAxios を追加するには、ターミナルを開き、ディレクトリをこのプロジェクトに変更します。
- cd digital-ocean-tutorial
 
その後、このコマンドを実行してAxiosをインストールします。
- npm install axios
 
次に、Axios を使用するファイルにインポートする必要があります。
GET リクエストを実行するこの例では、新しいコンポーネントを作成し、そのコンポーネントにAxios をインポートしてGET リクエストを送信します。
React プロジェクトの src フォルダ内に、PersonList.js という名前のコンポーネントを作成します。
- nano src/PersonList.js
 
次のコードをコンポーネントに追加します。
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
  state = {
    persons: []
  }
  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res => {
        const persons = res.data;
        this.setState({ persons });
      })
  }
  render() {
    return (
      <ul>
        { this.state.persons.map(person => <li>{person.name}</li>)}
      </ul>
    )
  }
}
まず、React と Axios をインポートして、両方をコンポーネントで使用できるようにします。次に、componentDidMount のライフサイクルフックを使用して、GET リクエストを実行します。
axios.get(url)をAPI エンドポイントのURL と組み合わせて使用すると、応答オブジェクトを返すpromiseを取得します。応答オブジェクト内には、personの値が割り当てられるデータがあります。
res.status を基にステータスコードや、res.request 内の詳細情報など、リクエストに関するその他の情報を取得することもできます。
POST リクエストを実行するこのステップでは、POSTと呼ばれる別のHTTPリクエストメソッドを使用してAxiosを使用します。
PersonList 内の前のコードを削除し、次のコードを追加してユーザー入力可能なフォームを作成し、その後コンテンツをAPIに POST します。
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
  state = {
    name: '',
  }
  handleChange = event => {
    this.setState({ name: event.target.value });
  }
  handleSubmit = event => {
    event.preventDefault();
    const user = {
      name: this.state.name
    };
    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person Name:
            <input type="text" name="name" onChange={this.handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}
handleSubmit関数内で、フォームのデフォルトの動作を無効にします。その後、stateをuser入力に更新します。
POSTを使用すると、thenコール内で使用できる情報を含む同じ応答オブジェクトを取得できます。
POSTリクエストを完了するには、まず、user入力をキャプチャします。次に、POSTリクエストと共に入力を追加すると、応答が得られます。次に、console.log 応答を使用して、フォームに user 入力を表示できます。
DELETE リクエストを実行するこの例では、axios.deleteを使用して API から項目を削除し、URLをパラメータとして渡す方法を説明します。
フォームのコードをPOST の例から変更して、新しいユーザーを追加する代わりにユーザーを削除します。
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
  state = {
    id: '',
  }
  handleChange = event => {
    this.setState({ id: event.target.value });
  }
  handleSubmit = event => {
    event.preventDefault();
    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person ID:
            <input type="text" name="id" onChange={this.handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    )
  }
}
この場合も、res オブジェクトは、リクエストに関する情報を提供します。その後、フォームの送信後に、console.log にその情報を再度表示できます。
この例では、URLとその他の設定要素を定義できる_baseインスタンス_を設定する方法を説明します。
api.js という名前の別のファイルを作成します。
- nano src/api.js
 
次のデフォルトを使用して、新しいaxios インスタンスをエクスポートします。
import axios from 'axios';
export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`
});
デフォルトインスタンスを設定すると、PersonList コンポーネント内で使用できるようになります。次のように新しいインスタンスをインポートします。
import React from 'react';
import axios from 'axios';
import API from '../api';
export default class PersonList extends React.Component {
  handleSubmit = event => {
    event.preventDefault();
    API.delete(`users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }
}
http://jsonplaceholder.typicode.com/ が、ベース URL になっているため、APIで別のエンドポイントにアクセスするたびにURL全体を入力する必要がなくなりました。
async および await を使用するこの例では、promiseを処理するために、async およびawait の操作方法を説明します。
await キーワードは、promiseを解決し値を返します。その後、値を変数に割り当てることができます。
handleSubmit = async event => {
  event.preventDefault();
  //
  const response = await API.delete(`users/${this.state.id}`);
  console.log(response);
  console.log(response.data);
};
このコードサンプルでは、.then() が置き換えられています。promiseは解決され、値はresponse変数内に格納されます。
このチュートリアルでは、Reactアプリケーション内でAxiosを使用してHTTPリクエストを作成し、応答を処理する方法の例をいくつか見てきました。
Reactについての詳細については、React.js でのコーディング方法シリーズを参照するか、またはReact トピックページでより多くの演習とプログラミングプロジェクトをご覧ください。
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
I create educational content over at YouTube and https://developer.school.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.