axios 和 fetch异同点

发布于:2025-03-18 ⋅ 阅读:(20) ⋅ 点赞:(0)

axiosfetch 都是用于在浏览器和 Node.js 中发起 HTTP 请求的工具,但它们有一些关键区别。以下是它们的异同点,并通过示例说明如何使用它们。


相同点

  1. 用途:都用于发起 HTTP 请求(如 GET、POST 等)。
  2. 支持 Promise:都基于 Promise,支持异步操作。
  3. 跨平台:都可以在浏览器和 Node.js 中使用(fetch 在 Node.js 中需要额外的 polyfill,如 node-fetch)。
  4. 支持现代浏览器:两者在现代浏览器中都能使用。

不同点

特性 fetch axios
API 设计 原生 API,较为底层,需要手动处理一些细节(如 JSON 解析、错误处理)。 封装更高级,API 设计更友好,功能更丰富。
错误处理 只有网络错误才会 reject,HTTP 错误(如 404、500)需要手动处理。 HTTP 错误(如 404、500)会自动 reject。
请求取消 需要使用 AbortController 内置支持请求取消,使用 CancelToken(旧版)或 AbortController(新版)。
拦截器 不支持。 支持请求和响应拦截器。
自动 JSON 转换 需要手动调用 .json() 方法。 自动将响应数据转换为 JSON。
请求进度 不支持。 支持上传和下载进度监控。
浏览器兼容性 现代浏览器支持良好,IE 不支持。 兼容性更好,支持更广泛的浏览器(包括 IE)。
体积 原生 API,无需额外安装。 需要安装,体积较大(约 13KB)。

示例对比

1. GET 请求

使用 fetch
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json(); // 手动解析 JSON
    })
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
使用 axios
axios.get('https://api.example.com/data')
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));

2. POST 请求

使用 fetch
fetch('https://api.example.com/data', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name: 'John', age: 30 }), // 手动序列化
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
使用 axios
axios.post('https://api.example.com/data', { name: 'John', age: 30 })
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));

3. 错误处理

使用 fetch
fetch('https://api.example.com/invalid-endpoint')
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
使用 axios
axios.get('https://api.example.com/invalid-endpoint')
    .then(response => console.log(response.data))
    .catch(error => {
        if (error.response) {
            console.error('HTTP error! status:', error.response.status);
        } else {
            console.error('Error:', error.message);
        }
    });

4. 请求取消

使用 fetch
const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', { signal })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

// 取消请求
controller.abort();
使用 axios
const controller = new AbortController();

axios.get('https://api.example.com/data', { signal: controller.signal })
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));

// 取消请求
controller.abort();

5. 拦截器

使用 fetch

fetch 不支持拦截器,需要手动封装。

使用 axios
// 请求拦截器
axios.interceptors.request.use(config => {
    console.log('Request sent:', config);
    return config;
});

// 响应拦截器
axios.interceptors.response.use(response => {
    console.log('Response received:', response);
    return response;
});

axios.get('https://api.example.com/data')
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));

总结

  • fetch

    • 原生 API,无需额外依赖。
    • 更底层,需要手动处理 JSON 解析、错误处理等。
    • 适合简单的请求场景,或对包体积敏感的项目。
  • axios

    • 功能更强大,API 更友好。
    • 支持拦截器、自动 JSON 转换、请求取消等高级功能。
    • 适合需要复杂功能(如拦截器、进度监控)的项目。

根据项目需求选择合适的技术:

  • 如果是现代浏览器环境且需要轻量级解决方案,可以选择 fetch
  • 如果需要更强大的功能和更好的兼容性,可以选择 axios