axios 和 fetch异同点

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
javascript 复制代码
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
javascript 复制代码
axios.get('https://api.example.com/data')
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));

2. POST 请求

使用 fetch
javascript 复制代码
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
javascript 复制代码
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
javascript 复制代码
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
javascript 复制代码
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
javascript 复制代码
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
javascript 复制代码
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
javascript 复制代码
// 请求拦截器
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
相关推荐
Coffeeee3 分钟前
一个kotlin的Smart cast导致的编译问题
android·前端·kotlin
CodeSheep11 分钟前
胡彦斌都开始苦修Vibe Coding,还上架App Store,都卷到编程来了吗?
前端·后端·程序员
薄荷椰果抹茶12 分钟前
前端技术之---打字机效果与流式输出
前端
Mintopia14 分钟前
Tanstack为什么会火
前端
DongWook15 分钟前
关于Harness Engineering的一次实践
前端·后端
风骏时光牛马16 分钟前
Kotlin开发高频疑难问题汇总梳理
前端
暗冰ཏོ16 分钟前
ECharts 前端图表开发全攻略:参数配置、项目实战与高级可视化资源整理
前端·vue.js·echarts·visual studio code
PILIPALAPENG19 分钟前
gh:终端里的GitHub总控台,AI时代的开发者神器
前端·人工智能·后端
用户0595401744625 分钟前
Redis持久化踩坑实录:RDB+AOF混合持久化,竟会悄无声息丢数据?我用pytest+Docker复现了30次故障场景
前端·css
浮游本尊27 分钟前
项目全景 + 第一条完整后端链路
java·前端