ホームページ  >  記事  >  ウェブフロントエンド  >  axios における非同期リクエストのプロセスと原則の詳細な分析

axios における非同期リクエストのプロセスと原則の詳細な分析

藏色散人
藏色散人転載
2022-08-09 15:30:463210ブラウズ

1.axios とは何ですか?

axios は、get、post、その他のリクエストを送信できる Promise ベースのメソッドで、フロントエンドとバックエンドの両方で使用できます。 [推奨: Ajax ビデオ チュートリアル Web フロントエンド ]

2. axios の内部原理

  • axiosライブラリが外部に公開されている axios インスタンスがマウントされ、axios インスタンスに Axios メソッドがマウントされている Axios メソッドには、interceptors オブジェクト (インターセプター) と interceptors オブジェクト ## があります# には request オブジェクト response オブジェクト があり、request オブジェクト response オブジェクト には両方とも use メソッドがあるため、axios を呼び出すことができます。 interceptors.request.use() および axios.interceptors .response.use().

  • ##interceptors オブジェクト

    request オブジェクトおよび 応答オブジェクト は、実際にはインターセプター (ハンドラー) の配列を管理するために使用されます。 axios.interceptors.request.use() を呼び出すと、成功コールバックと失敗コールバックがリクエストのインターセプター配列 (ハンドラー) にプッシュされます。使用されるたびに、[res1, rej1, res2, rej2...] のように 1 回プッシュされます。

  • 次はチェーンです。
  • これは配列です。すべてのコールバックを格納する

    Promiseに使用するため、の2つの値を使用する必要があり、初期値はdispatchRequestとundefiendです。次に、Promise.resolve(config).then(fn1, fn2)。 config の結果が満たされる (成功する) と、config の設定が fn1 に渡されて実行されます。拒否(エラー報告)の場合は、エラー結果を fn2 に渡して実行します(Promise.resolve(config).then(chain[0],chain[1]))。 chain[0] は成功のコールバック、chain[1] は失敗のコールバックです。 config には多くの設定項目があり、それらは文字列値やメソッドなどです。

  • 次のステップは、すべての Promise を整理し、
  • request 配列

    内のコールバック関数を chain 配列 の先頭にシフト解除することです。 、## を移動します。 #response array のコールバック関数は、chain array の最後にプッシュされます。最後の chain array は、[res2, rej2, res1, rej1,dispatchRequest, undefiend, res3, rej3, res4, rej4] に似ています。

  • dispatchRequest
  • axios.request の実行に使用され、dispatchRequest メソッドには adapter が含まれています、異なる環境に応じて異なるオブジェクトを呼び出します。ブラウザ環境の場合は、XMLHttpRequest オブジェクトを呼び出します。 Nodejs 環境の場合は、http object を呼び出します。そのため、フロントエンドとバックエンドの両方で使用できます。 adapter は要求されたデータを解析してカプセル化します。カプセル化されたオブジェクトは、私たちが確認できる response 応答オブジェクト です。

  • dispatchRequest
  • の処理後、

    interceptors.response のコールバック関数が実行されます。これが、後者の interceptors.request が前者の interceptors.requets より前に実行され、次に axios.request という実行順序になっている理由です。 interceptors.response.

    を順番に実行してから、ビジネス ロジックを実行します。
  • 3. axios の使用

1. axios を使用する

一般的なメソッド: get、post、request

axios.get

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

axios.post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios.request

は多数で渡すことができますrequest Configurations

axios.request({
	url: '/user',
	method: 'get', // 默认
	baseURL: '/api',
	//...})

2. 構成メソッドを渡します

axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
4. 応答モジュール応答モジュールには次のパラメータがあります

{
	data: {},
	status: 200,
	statusText: 'ok',
	header: {},
	config: {},
	request: {}}

5. 構成

1. グローバル axios 構成

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
2. インスタンス構成

const instance = axios.create({
  baseURL: 'https://api.example.com'});
 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
3. 設定の優先順位

#

const instance = axios.create();instance.defaults.timeout = 2500;instance.get('/longRequest', {
  timeout: 5000});
最終タイムアウト設定時間は 5000 であるため、ここでの優先順位はリクエストの設定 > インスタンス化設定 > axios のデフォルト設定6. インターセプター

データをリクエストする前またはデータを受信する前にデータを処理できる

axios.interceptors.request.use(function (config) {
    return config;
  }, function (error) {
    return Promise.reject(error);
  });
  axios.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
    return Promise.reject(error);
  });

7. リクエストの同時処理

// 把axios请求放进函数里function getUserAccount() {
  return axios.get('/user/12345');}
 function getUserPermissions() {
  return axios.get('/user/12345/permissions');}//函数执行放到Promise里面排队,挨个响应。Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });
参考ドキュメント: https://www.npmjs.com/package/axios

以上がaxios における非同期リクエストのプロセスと原則の詳細な分析の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はcsdn.netで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。