Fetch と Axios の違いは何ですか?

        Axios は XMLHttpRequest のカプセル化です。

        Fetch は、XMLHttpRequest のカプセル化ではなく、リソースを取得するための新しいインターフェイス メソッドです。

        最大の違いは、Fetch はブラウザーでネイティブにサポートされているのに対し、Axios は Axios ライブラリを導入する必要があることです。

1. リクエスト方法

      Axios は、リクエスト URL とリクエスト メソッド、パラメータを含むオブジェクトを渡します。

      fetch は 2 つのパラメータを渡します。1 つ目はリクエスト URL、2 つ目はリクエストの一部のパラメータです。

1. Axios请求示例:

const options = {
  url: "http://example.com/",
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json;charset=UTF-8",
  },
  data: {
    a: 10,
    b: 20,
  },
};

axios(options).then((response) => {
  console.log(response.status);
});


2. Fetch请求示例:

const url = "http://example.com/";
const options = {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json;charset=UTF-8",
  },
  body: JSON.stringify({
    a: 10,
    b: 20,
  }),
};

fetch(url, options).then((response) => {
  console.log(response.status);
});

2. 応答タイムアウト

        Axios リクエストはタイムアウト属性を直接設定して、応答タイムアウトを制御できます。

        フェッチリクエストではAbortController属性を使用する必要がありますが、axios ほど便利ではありません

axios({
  method: "post",
  url: "http://example.com/",
  timeout: 4000, // 请求4秒无响应则会超时
  data: {
    firstName: "David",
    lastName: "Pollock",
  },
})
  .then((response) => {
    /* 处理响应 */
  })
  .catch((error) => console.error("请求超时"));


const controller = new AbortController();

const options = {
  method: "POST",
  signal: controller.signal,
  body: JSON.stringify({
    firstName: "David",
    lastName: "Pollock",
  }),
};
const promise = fetch("http://example.com/", options);

// 如果4秒钟没有响应则超时
const timeoutId = setTimeout(() => controller.abort(), 4000);

promise
  .then((response) => {
    /* 处理响应 */
  })
  .catch((error) => console.error("请求超时"));

3. データの変換

        Axios のもう 1 つの優れた点は、データが自動的に変換されることですが、Fetch は異なり、ユーザーが手動で変換する必要があることです。

// axios
axios.get("http://example.com/").then(
  (response) => {
    console.log(response.data);
  },
  (error) => {
    console.log(error);
  }
);

// fetch
fetch("http://example.com/")
  .then((response) => response.json()) // 需要对响应数据进行转换
  .then((data) => {
    console.log(data);
  })
  .catch((error) => console.error(error));

4.  HTTP インターセプター

        Axios はリクエストと対応するインターセプターを提供します

        Fetch にはインターセプタ関数はありませんが、この関数の実装は難しくなく、グローバル Fetch メソッドを直接書き換えるだけです。

fetch = ((originalFetch) => {
  return (...arguments) => {
    const result = originalFetch.apply(this, arguments);
    return result.then(console.log("请求已发送"));
  };
})(fetch);

fetch("http://example.com/")
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
  });

5. 同時リクエスト

        アクシオス:

axios
  .all([
    axios.get("https://api.github.com/users/iliakan"),
    axios.get("https://api.github.com/users/taylorotwell"),
  ])
  .then(
    axios.spread((obj1, obj2) => {
      ...
    })
  );

        フェッチ:

Promise.all([
  fetch("https://api.github.com/users/iliakan"),
  fetch("https://api.github.com/users/taylorotwell"),
])
  .then(async ([res1, res2]) => {
    const a = await res1.json();
    const b = await res2.json();
  })
  .catch((error) => {
    console.log(error);
  });

6. ブラウザのネイティブサポート

        Fetch が Axios に勝る唯一の点は、最新のブラウザでのネイティブ サポートです。

        現在の Web ページで Chrome のコンソールを開き、Fetch を使用して、構成を行わずに直接リクエストを作成します。

個人的な要約:       

        1. プロジェクトで使うならやはりAxiosを使うのが便利

        2. ブラウザ コンソールでテストしている場合、またはすぐにリクエストしたい場合は、インポートする必要がなく、ブラウザでサポートされているため、Fetch を使用できます。

おすすめ

転載: blog.csdn.net/weixin_48309048/article/details/126523603