Fetch与Axios:区别、联系、优缺点及使用差异

发布于:2025-06-08 ⋅ 阅读:(17) ⋅ 点赞:(0)

Fetch与Axios:区别、联系、优缺点及使用差异

在现代Web开发中,数据交互是必不可少的环节。Fetch API和Axios是两种常用的HTTP客户端工具,用于在浏览器和Node.js环境中发起HTTP请求。下面我们来详细探讨它们的区别、联系、优缺点以及使用上的差异。

一、联系

Fetch API和Axios的主要目的都是发起HTTP请求,实现客户端与服务器之间的数据交互。它们都支持常见的HTTP方法,如GET、POST、PUT、DELETE等,并且可以处理各种类型的响应数据,如JSON、文本、二进制数据等。

二、区别

1. 浏览器支持与兼容性

  • Fetch API:是现代浏览器原生支持的API,无需额外引入库。但在旧版本的浏览器(如IE)中不支持,需要使用polyfill来实现兼容性。
  • Axios:是一个第三方库,需要引入才能使用。它支持所有主流浏览器,包括旧版本的IE,并且在Node.js环境中也能使用。

2. 响应处理

  • Fetch API:返回的是一个Promise对象,需要手动解析响应数据。例如,要获取JSON格式的响应数据,需要调用response.json()方法。
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
  • Axios:会自动解析响应数据,默认情况下返回的就是解析后的JSON对象。
axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

3. 请求拦截和响应拦截

  • Fetch API:本身不支持请求拦截和响应拦截,需要手动实现。
  • Axios:内置了请求拦截和响应拦截功能,可以在请求发送前和响应返回后进行一些处理,如添加请求头、错误处理等。
// 请求拦截
axios.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  config.headers.Authorization = 'Bearer ' + token;
  return config;
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 响应拦截
axios.interceptors.response.use(response => {
  // 对响应数据做点什么
  return response;
}, error => {
  // 对响应错误做点什么
  return Promise.reject(error);
});

4. 错误处理

  • Fetch API:只有在网络请求失败时才会reject Promise,即使服务器返回404、500等状态码,Promise仍然会resolve。需要手动检查response.ok属性来判断请求是否成功。
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));
  • Axios:在请求失败时会reject Promise,并且会包含详细的错误信息,如状态码、错误消息等。
axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => {
    if (error.response) {
      // 请求已发出,但服务器响应状态码不在 2xx 范围内
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 请求已发出,但没有收到响应
      console.log(error.request);
    } else {
      // 其他错误
      console.log('Error', error.message);
    }
  });

三、优缺点

1. Fetch API

优点
  • 原生支持,无需引入额外库,减少项目体积。
  • 语法简洁,符合现代JavaScript的Promise风格。
缺点
  • 浏览器兼容性差,需要polyfill。
  • 响应处理繁琐,需要手动解析。
  • 错误处理不够直观。

2. Axios

优点
  • 支持所有主流浏览器和Node.js环境。
  • 内置请求拦截和响应拦截功能,方便处理请求和响应。
  • 自动解析响应数据,错误处理更完善。
  • 支持取消请求、自动转换JSON数据等功能。
缺点
  • 需要引入第三方库,增加项目体积。

四、使用上的差异和特性

1. 发送POST请求

  • Fetch API
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
  • Axios
axios.post('https://api.example.com/data', { key: 'value' })
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

2. 取消请求

  • Fetch API:使用AbortController实现超时取消请求。
const controller = new AbortController();
const signal = controller.signal;

// 设置超时时间为3000毫秒
const timeoutId = setTimeout(() => {
  controller.abort();
}, 3000);

fetch('https://api.example.com/data', { signal })
  .then(response => {
    clearTimeout(timeoutId);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('请求超时被取消');
    } else {
      console.error(error);
    }
  });
  • Axios:使用CancelToken实现超时取消请求。
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

// 设置超时时间为3000毫秒
const timeoutId = setTimeout(() => {
  source.cancel('请求超时被取消');
}, 3000);

axios.get('https://api.example.com/data', {
  cancelToken: source.token
})
  .then(response => {
    clearTimeout(timeoutId);
    console.log(response.data);
  })
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log(error.message);
    } else {
      console.error(error);
    }
  });

总结

Fetch API和Axios各有优缺点,选择使用哪一个取决于项目的具体需求。如果项目对浏览器兼容性要求不高,且希望减少依赖,可以选择Fetch API;如果需要处理复杂的请求和响应,或者需要支持旧版本的浏览器,Axios是更好的选择。