nomurabbitのブログ

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

nomurabbitのブログ

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

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

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

Part6の今回は初期configについてです。Typescriptの解説やサンプルコードを交えて一緒に勉強していきましょう

Config Defaults

You can specify config defaults that will be applied to every request.

すべてのHTTPリクエストに共通した初期configを定義できます。axios全体に初期configを定義する場合はこのように行います。

Global axios defaults

axios.defaults.baseURL = 'https://api.example.com';

// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
// See below for an example using Custom instance defaults instead.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Custom instance defaults

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

それぞれTypescriptでサンプルを書くとするとこんな感じです。

Global axios defaults nomurabbit ver. (Typescript)

axios.defaults.baseURL = apiUrl_dammy_base;

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

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

実行結果
f:id:nomurabbit:20211228160200p:plain

Custom instance defaults nomurabbit ver. (Typescript)

axios.defaults.baseURL = apiUrl_dammy_base;

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

instance.defaults.baseURL = apiUrl_dammy_base;

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

実行結果
f:id:nomurabbit:20211228160739p:plain

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.

configがマージされる場合はデフォルトの初期config < ユーザー定義の初期config < リクエスト時の引数の順に優先順位が高くなります。

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});|

Typescriptで実験してみましょう。

sample nomurabbit ver.

const apiUrl_dammy = "https://dammy/api/fuga";

axios.defaults.timeout = 1000;

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

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

実行結果
f:id:nomurabbit:20211228161214p:plain

timeoutがリクエスト時の引数の値で上書きされていますね。

というわけで今回は初期configについて勉強してきましたが、axiosのREADME読んでみた Part6いかがでしたでしょうか?

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

参考

axios
github.com