Fetch和Axios到底有什么区别

        Axios是对XMLHttpRequest的封装,

        Fetch是一种新的获取资源的接口方式,并不是对XMLHttpRequest的封装。

        最大的不同点在于Fetch是浏览器原生支持,而Axios需要引入Axios库。

1. 请求方式

      axios传一个对象,里面包含请求url和请求方法,参数

      fetch传两个参数,第一个是请求url,第二个是请求的一些参数

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请求可以直接设置timeout属性来控制响应超时

        fetch请求需要使用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还有非常好的一点就是会自动对数据进行转化,而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:

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. 浏览器原生支持

        Fetch唯一碾压Axios的一点就是现代浏览器的原生支持。

        在当前网页打开Chrome的控制台使用Fetch几乎不需要什么配置就可以直接进行请求。

个人总结:       

        1. 如果在项目中使用的话还是Axios使用起来方便

        2. 如果是在浏览器控制台测试,或者想快速请求的话,可以使用Fetch,因为它不需要导入,是浏览器支持的。

猜你喜欢

转载自blog.csdn.net/weixin_48309048/article/details/126523603