当前位置: 首页 > article >正文

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

http://www.kler.cn/a/589718.html

相关文章:

  • Java继承与反思,单例模式与静态的思考
  • 【redis】Jedis 操作 Redis 基础指令(下)
  • Mysql中创建表时的约束条件
  • 力扣刷题——2181.合并零之间的节点
  • Java中的GC是什么?
  • STM32U575RIT6单片机(四)
  • 基于WebRTC与P2P技术,嵌入式视频通话EasyRTC实现智能硬件音视频交互,适配Linux、ARM、RTOS、LiteOS
  • 深度学习处理时间序列(1)
  • 嵌入式学习笔记-C语言知识点:栈的作用,C语言函数参数的入栈顺序,C++ 拷贝构造函数,数组名和指针的区别与联系,指针运算,指针和引用
  • Apache Spark_解决生产环境数据倾斜问题方案及思路
  • Tomcat新手入门指南:从零开始安装与基本配置
  • Python驱动CATIA自动化建模:科赫雪花算法实现与工程应用
  • 《解锁华为黑科技:MindSpore+鸿蒙深度集成奥秘》
  • 咪咕MG101_晨星MSO9380芯片_安卓5.1.1_免拆卡刷固件包
  • Bash语言的手动测试
  • Keepalived 多主模型与 LVS 高可用
  • 基于System V的共享内存函数使用指南
  • Flume详解——介绍、部署与使用
  • 2025深圳国际数字能源展全球招商启动,9月18日盛大开启
  • XGPT x DeepSeek:微步AI安全助手满血升级