What is the difference between Fetch and Axios?

        Axios is an encapsulation of XMLHttpRequest,

        Fetch is a new interface method for obtaining resources, not an encapsulation of XMLHttpRequest.

        The biggest difference is that Fetch is natively supported by browsers, while Axios needs to introduce the Axios library.

1.  Request method

      Axios passes an object, which contains request url and request method, parameters

      fetch passes two parameters, the first is the request url, and the second is some parameters of the request

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.  Response timeout

        Axios requests can directly set the timeout attribute to control the response timeout

        Fetch requests need to use AbortControllerattributes, which are not as convenient as 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.  Transformation of data

        Another very good thing about Axios is that it will automatically convert the data, but Fetch is different, it requires the user to manually convert.

// 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 Interceptor

        Axios provides requests and corresponding interceptors

        Fetch does not have an interceptor function, but it is not difficult to implement this function, just rewrite the global Fetch method directly.

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.  Simultaneous requests

        Axios:

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

        Fetch:

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.  Browser native support

        The only thing Fetch beats Axios is native support in modern browsers.

        Open Chrome's console on the current web page and use Fetch to make requests directly without any configuration.

Personal summary:       

        1. If it is used in the project, it is still convenient to use Axios

        2. If you are testing in the browser console, or want to request quickly, you can use Fetch, because it does not need to be imported and is supported by the browser.

Guess you like

Origin blog.csdn.net/weixin_48309048/article/details/126523603
Recommended