axios 和 fetch异同点

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


相同点

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

不同点

特性fetchaxios
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值