axiosを封装して使用する方法は何ですか?

axiosのエンベロープ化および使用方法は次の通りです:

  1. axiosのインストール:以下のコマンドをターミナルで実行してaxiosライブラリをインストールしてください。
npm install axios
  1. axiosを導入する際には、必要なファイルで以下のコードを使用します。
import axios from 'axios';
  1. 手に入れる
axios.get('/api/mydata')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
  1. 投稿
axios.post('/api/mydata', { name: 'John', age: 30 })
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
  1. デフォルトのヘッダー
axios.defaults.headers.common['Authorization'] = 'Bearer TOKEN';
  1. インターセプターのリクエスト
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
  1. レスポンスをインターセプトする
axios.interceptors.response.use(function (response) {
  // 对响应数据做些什么
  return response;
}, function (error) {
  // 对响应错误做些什么
  return Promise.reject(error);
});

これらはaxiosの基本的なメソッドをパッケージ化し使用する方法です。必要に応じてさらなる構成や使用が可能です。

bannerAds