nomurabbitのブログ

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

nomurabbitのブログ

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

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

こんにちは!nomurabbitです。今回はaxiosに関する記事です。

Part5の今回はHTTPメソッドの投げ方についてです。axios.get()axios.request()以外にも実装があるんです。Typescriptの解説やサンプルコードを交えて一緒に勉強していきましょう

axios API

Requests can be made by passing the relevant config to axios.

configをaxiosに渡してHTTPリクエストを実現できます。実際READMEにはこのようなサンプルコードが載っています。

無名メソッドaxios(config)でPOSTを投げる例

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

無名メソッドaxios(config)でGETを投げる例

// GET request for remote image in node.js
axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

無名メソッドaxios(url,[config])でGETを投げる例

// Send a GET request (default method)
axios('/user/12345');

axiosの定義を見ると無名関数が2つ定義されています。(config: AxiosRequestConfig): AxiosPromise;(url: string, config?: AxiosRequestConfig): AxiosPromise;です。

一つ目はconfigのみを引数にとる例です。AxiosRequestConfigの定義を見ると、プロパティはすべて任意となっていますが、この場合config内でurlの指定は必須です。

二つ目はurlを第一引数、configを第二引数にとる例です。この場合urlの指定は必須、configの指定は任意となります。

configのinterfaceの定義を載せておきます。

export interface AxiosRequestConfig<D = any> {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
  transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
  headers?: AxiosRequestHeaders;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: D;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: ((status: number) => boolean) | null;
  maxBodyLength?: number;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
  decompress?: boolean;
  transitional?: TransitionalOptions;
  signal?: AbortSignal;
  insecureHTTPParser?: boolean;
}

axiosの無名関数の定義は下記の通りです。

export interface AxiosInstance extends Axios {
  (config: AxiosRequestConfig): AxiosPromise;
  (url: string, config?: AxiosRequestConfig): AxiosPromise;
}

export interface AxiosStatic extends AxiosInstance {
  create(config?: AxiosRequestConfig): AxiosInstance;
  Cancel: CancelStatic;
  CancelToken: CancelTokenStatic;
  Axios: typeof Axios;
  readonly VERSION: string;
  isCancel(value: any): boolean;
  all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
  isAxiosError(payload: any): payload is AxiosError;
}

declare const axios: AxiosStatic;

これらの無名関数をtypescriptで実装すると、このようになります。

axios(config)の例 nomurabbit ver.

const getHttpPostResponseBbk = () => {
  axios({
    url:apiUrl,
    method: 'post',
    headers: {
      'Content-Type': 'text/plain',
      'Authorization': 'token12345678'
    },
    data: {httpRequestMessage},
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

axios(url, config)の例 nomurabbit ver.

const getHttpPostResponseBbk = () => {
  axios(apiUrl, {
    method: 'post',
    headers: {
      'Content-Type': 'text/plain',
      'Authorization': 'token12345678'
    },
    data: {httpRequestMessage},
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

Request method aliases

For convenience aliases have been provided for all supported request methods.

axiosは全てのHTTPメソッドに対してエイリアスを持ちます。

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

When using the alias methods url, method, and data properties don't need to be specified in config.

エイリアスの引数にurlやdataを渡す場合は、config内で改めて指定する必要はないということですね。

Concurrency (Deprecated)

Please use Promise.all to replace the below functions.
Helper functions for dealing with concurrent requests.
axios.all(iterable) axios.spread(callback)

メソッドを同時に実行したいときはaxios.allやaxios.spreadではなくPromise.allを使いましょうという注意書きです。

Creating an instance

You can create a new instance of axios with a custom config.

あらかじめconfigをカスタマイズした状態でaxiosのインスタンスを作れます。

axios.create([config])

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

baseURLを指定しておけるのは便利かもです!

Instance methods

The available instance methods are listed below. The specified config will be merged with the instance config.

axiosインスタンスには下記のメソッドが定義されています。引数に与えられたconfigはインスタンスのconfigとマージされます。

  • axios#request(config)
  • axios#get(url[, config])
  • axios#delete(url[, config])
  • axios#head(url[, config])
  • axios#options(url[, config])
  • axios#post(url[, data[, config]])
  • axios#put(url[, data[, config]])
  • axios#patch(url[, data[, config]])
  • axios#getUri([config])

configのマージについて実験してみましょう!

サンプルコード nomurabbit ver.

const apiUrl_dammy = "https://dammy/api/hoge";
const apiUrl = "https://url/api/sabrbbk";

const instance = axios.create({
  url: apiUrl_dammy,
  headers: {
    'Content-Type': 'text/plain'
  },
});

const getHttpPostResponseBbk = () => {
  instance.post(apiUrl, {
    data: {httpRequestMessage},
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

実験の内容を簡単にまとめると下記の2点です。

  1. インスタンスurlは引数のurl上書きされるのか?
  2. インスタンスで指定したheadersと引数で渡したdataはHTTPリクエストに組み込まれるのか?

実行してみましょう!

まずはurlですが、このように引数のurlで上書きされました。また、headersの内容はインスタンスから引き継がれています。

f:id:nomurabbit:20211228005240p:plain

さらに、dataについても引数の値がHTTPリクエストに組み込まれています。

f:id:nomurabbit:20211228005434p:plain

configのマージの挙動がよくわかりました。

というわけでHTTPメソッドの投げ方について勉強してきましたが、axiosのREADME読んでみた Part5いかがでしたでしょうか?

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

参考

axios
github.com