nomurabbitのブログ

nomurabbitのブログはITを中心にした技術ブログです。

nomurabbitのブログ

【Typescript】axiosのREADME読んでみた Part1【React】

この記事はReactaxiosを使うために、axiosのREADMEを読んで得た情報をまとまたものです。React×Typescriptのサンプルコードも載せています。

こんにちは!nomurabbitです。今日はnode.jsのHTTPクライアントであるaxiosについて、READMEを読んで勉強していきます。

使い方を身につけて、自由自在にHTTP通信しちゃいましょう!

axios

まずはaxiosの概要です。READMEの冒頭にこのような記述があります。

Promise based HTTP client for the browser and node.js

Promise based HTTP clientとあるように、axiosのメソッドの戻り値はPromiseで返ってきます。そのためaxiosの非同期処理は、then、catchでチェーンをつなげて実行順序をコントロールできます。

後ほどExampleの項でも解説します。

Features

次に、axiosの特徴です。

英語 ver.

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

和訳 ver. by nomurabbit

  • ブラウザからXMLHttpRequestsを投げます。
  • node.jsを使ってhttp requerstsを作ります。
  • PromiseをつかったAPIをサポートします。
  • request と responseの前にインターセプターが定義できます
  • 取得したrequest と responseのデータを変換できます。
  • requests を中止できます。
  • 自動的に JSON data から変換できます。
  • Client side は XSRF対策をサポートします。

各項目の具体的な内容は、このあと出てくるサンプルコードで試してみましょう。

Browser Support

2021/12/23時点で、ChromeFirefoxSafariOpera、Edge、IE11の最新バージョンに対応しています。

Installing

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using yarn:

$ yarn add axios

Using jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

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

このブログで使っているyarnでも、ばっちりインストールできますね。

Example

CommonJS usage

In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with require() use the following approach:

const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings

CommonJSのプロジェクトにimportをする時の注意事項です。Reactimportする時は、以下のようになります。

import nomurabbit ver.

import axios from 'axios';

続いてはメソッドごとの使い方紹介です。まずはaxios.get()から。公式ページではJSの書き方で紹介されています。前半の2つがthen()、catch()のメソッドチェーンを使った書き方で、最後の一つがasync/awaitを使った書き方です。

Performing a GET request

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

これを踏まえたうえでReactのサンプルコードがこちらです。

Reactサンプルコード nomruabbir ver. その1

import React from 'react';
import axios from 'axios';
import ResponsiveDrawer from '../components/layout/ResponsiveDrawer';

const Home = () => {

  const apiUrl = "https://api_no_url";

  const getHttpResponse = () => {
    axios.get(apiUrl)
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.log(error);
    });
  }
  
  return (
    <ResponsiveDrawer>
      <div>
        <p>home page.</p>
        <button onClick={() => getHttpResponse()}>
          Click me
        </button>
      </div>
    </ResponsiveDrawer>
  );
}
  
export default Home;

インポートは前述の通り、

import axios from 'axios';

と記載した上で、then()、catch()を使った書き方となっています。ここでaxios.get()がPromiseを返すので、then()およびcatch()ではそれぞれPromiseのresolve時rejectのコールバック関数を指定できます。

もう少し中身を見てみると、resolve時にコールバック関数に渡されるのがAxiosResponse型の引数で、reject時にに渡されるのがany型の引数です。

f:id:nomurabbit:20211224060827p:plain

なので、こんな感じでaxios.get()を成功させてやると、

f:id:nomurabbit:20211224055612p:plain

AxiosResponse型のインスタンスとして返ってきます。

f:id:nomurabbit:20211224060519p:plain

要素にアクセスするときは何も気にせずに "." で潜っていけばOKです。

f:id:nomurabbit:20211224060234p:plain

こんな感じ。

f:id:nomurabbit:20211224060339p:plain

逆にaxios.get()を失敗させてやると、

f:id:nomurabbit:20211224061031p:plain

こんな感じで返ってきます。

f:id:nomurabbit:20211224061316p:plain

実際のReactアプリで使うとなったらHTTPリクエストは副作用なので、useEffectを使ったほうがベターだと思います。こんな感じ。

Reactサンプルコード nomruabbir ver. その2

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import ResponsiveDrawer from '../components/layout/ResponsiveDrawer';

const Home = () => {

  const [httpRequestMessage, setHttpRequestMessage] = useState("");
  const apiUrl = "https://api_no_url";

  useEffect(() => {
    if(httpRequestMessage !== ""){
      axios.get(apiUrl + "?message=" + httpRequestMessage)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  },[httpRequestMessage]);
  
  return (
    <ResponsiveDrawer>
      <div>
        <p>home page.</p>
        <button onClick={() => setHttpRequestMessage("Hello")}>
          Click me
        </button>
      </div>
    </ResponsiveDrawer>
  );
}
  
export default Home;

Reactとaxiosについては、過去の記事でも取り扱っています。ぜひあわせてご覧ください。

nomurabbit.hatenablog.jp

というわけで、axiosのREADME読んでみた Part1いかがでしたでしょうか?次回以降、他のHTTPメソッドHTTPヘッダーのカスタマイズにも触れていきたいと思います。

次回もぜひご覧ください。では!